Kotlin contracts are a powerful feature introduced in Kotlin 1.3 to enhance code analysis and optimization. They provide a way for developers to give additional information to the compiler about the behavior of functions.
Contracts in Kotlin are declarations that describe the behavior of functions to the compiler. They help improve static analysis, enabling more precise null checks, smart casts, and other optimizations. By using contracts, developers can make their code more efficient and reduce the need for redundant checks.
To use contracts in Kotlin, you need to import the kotlin.contracts
package. Contracts are defined using the contract { ... }
function within a function body.
import kotlin.contracts.*
fun checkNotNull(value: Any?) {
contract {
returns() implies (value != null)
}
if (value == null) {
throw IllegalArgumentException("Value must not be null")
}
}
In this example, the contract states that if the function returns normally (doesn't throw an exception), it implies that the value
is not null.
Kotlin provides several predefined contract effects:
returns()
: Specifies conditions when the function returns normallyreturnsNotNull()
: Indicates that the function returns a non-null valuecallsInPlace()
: Specifies how many times a lambda parameter is calledThe callsInPlace()
effect is particularly useful for inline functions with lambda parameters:
inline fun withLock(lock: Lock, action: () -> T): T {
contract {
callsInPlace(action, InvocationKind.EXACTLY_ONCE)
}
lock.lock()
try {
return action()
} finally {
lock.unlock()
}
}
This contract informs the compiler that the action
lambda will be called exactly once, allowing for better optimization and analysis.
To fully understand and utilize Kotlin contracts, it's helpful to be familiar with these related concepts:
By mastering Kotlin contracts, you can write more efficient and expressive code, leveraging the full power of Kotlin's type system and compiler optimizations.