Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which are the benefits of Kotlin callsInPlace contract?

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.

like image 983
Luca Piccinelli Avatar asked Feb 01 '21 07:02

Luca Piccinelli


1 Answers

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.

like image 127
Михаил Нафталь Avatar answered Dec 13 '22 05:12

Михаил Нафталь