Which are the benefits of Kotlin callsInPlace contract?
Asked Answered
T

1

10

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.

Terrapin answered 1/2, 2021 at 7:4 Comment(0)
C
19

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:

  1. value to x will be assigned exactly once (it's prohibited to reassign value of val, even with the same value).
  2. 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.

Centrifuge answered 1/2, 2021 at 8:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.