1

why can't kotlin infer when an object is not null through the boolean in which it was checked? In this example, there should be no condition in which melons is null.

val berries = 13
val melons: String? = "big melons"
val condition: Boolean = berries >= 13 && melons != null

fun testerThing() { // compiles
    if (berries >= 13 && melons != null) { 
        doSomething(melons)
    }
}

fun testerThing2() { // doesn't compile
    if (condition) { 
        doSomething(melons)
    }
}
  • 3
    It’s simply too indirect. The compiler isn’t that sophisticated. – Tenfour04 Feb 01 '22 at 05:13
  • this code compiles fine with me. EDIT: nevermind, I assumened `doSomething` was a function that accepts `String?`. If it only accepts `String` you're right – Ivo Feb 01 '22 at 07:39

1 Answers1

1

Because the comparison isn't in your function testerThing2.

According to contracts' document,

Contracts primarily consider the behavior of methods rather than the properties of values. Properties of values should be handled by the type system rather than contracts.

And also,

Currently, Kotlin Contracts is a completely compile-time mechanism. There are no plans on bringing it to the run-time in the near future

So the compiler is conservative because it needs to guarantee that the code generated will work correctly in all potential scenarios. That is, the contracts only apply very explicitly.

James Lan
  • 248
  • 2
  • 8