Can anyone explain to me which are the benefits of Kotlin callsInPlace
contract? How the compiler takes advantage of knowing that the lambda function will get called in place? Also, the developer get any benefit from it? Like smartcast or so?
Thank you in advance.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With