Indirect inference of constraint

If you write

val id: String? = ...
if (id != null) {
    // Kotlin knows that id is not null here
}

but if you write

val id1: String? = ...
val id2: String? = ...
val bothDefined = id1 != null && id2 != null
if (bothDefined) {
    // Kotlin does not know that both id1 and id2 are not null here
}

You could create a function with a contract instead of using a Boolean variable.

If I understand correctly, you’re wanting the compiler to bake in a contract to values in some way. That would be cool.

Maybe there are more usecases from normal contracts that would work for playing around with the idea. You might find better discussion under the contract KEEP.

2 Likes