Guarantee that function arg gets called?

Can I tell the compiler that the function argument f is always called, in order to fix the error about the uninitialized variable x?

fun buildStuff(f: () -> Unit) {
    ...  f() ...
}

var x: Foo
buildStuff {
    x = ...
}
return x // ← error: Variable 'x' must be initialized

Yes and no. It is possible, but it is still an experimental feature.


That said, the functionality of contracts is stable. It’s already used in the standard library and I think the kotlin team guarantees that compiled code with contracts will not break in the future.
Only the syntax to create contracts might change in the future.

1 Like

Thanks, that’s a pleasant surprise. I didn’t know about contracts.

Kotlin is a great language.