How do I express in a contract that a condition is true inside a lambda? As in, I want to combine the power of
returns
with
callsInPlace
. For instance, I have an inline higher-order function that takes an
enabled: Boolean
parameter, and it
only calls the block passed to it if
enabled
is true. How do I say that
enabled
is
true
inside of the
block
?
E.g.:
@OptIn(ExperimentalContracts::class)
inline fun runIf(condition: Boolean, block: () -> Unit) {
contract {
callsInPlace(block, InvocationKind.AT_MOST_ONCE)
}
if(condition) block()
}
fun main() {
val test: String? = "Hello"
runIf(test != null) {
test.length
}
}
Yes that example is stupid, but my use-case provides parameters to
block
and hence it can't just return a
Boolean