This contract is not just telling compiler that lambda get called in place, but also (optionally) the amount of times it get called. This allows to compile some code that was uncompilable before contracts were intoduced in Kotlin 1.3.
Example from Dmitry Savvinov's talk (warning, it's in russian) about usage of this contract in stdlib:
public inline fun <R> run(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
fun foo() {
val x: Int
run {
x = 42 //Error in 1.2, ok in 1.3
}
println(x) //Error in 1.2, ok in 1.3
}
With this contract compiler knows that:
- value to
x
will be assigned exactly once (it's prohibited to reassign value of val
, even with the same value).
x
would be initialized by the time of println(x)
call (lambda is not just passed into run
function, but is actually called inside of it).
Previously, compiler was not sure about these things and issued error just in case.