How do I express in a contract that a condition is...
# stdlib
y
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.:
Copy code
@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
d
We plan to implement this feature after release of 2.0
thank you color 2
s
Not sure if it’s related but I’m Arrow we also define contracts in some places and it doesn’t work outside of the Arrow compilation unit. So downstream projects cannot benefit from it, https://github.com/arrow-kt/arrow/blob/b1ad7f713a68c24c8ae0105cbc4d2c9409e575ff/arrow-libs/core/arrow-core/src/commonMain/kotlin/arrow/core/Either.kt#L518 After checking
if(either.isRight())
I would expect to be able to access the
value
property of
Either.Right
. Is this related?