gian
03/06/2020, 8:43 AMfun main() {
val foo: Foo? = Foo("")
if (foo?.bar != null && foo.bar.isNotEmpty()) {
println(foo.bar.length) // smart cast
}
if (!foo?.bar.isNullOrEmpty()) {
println(foo.bar.length) // no smart cast
}
}
class Foo(val bar: String?)
Oscar
03/06/2020, 8:54 AMfoo?.bar
to an intermediate val and do the check thereFranSoto
03/06/2020, 8:54 AMgian
03/06/2020, 8:55 AMFranSoto
03/06/2020, 8:55 AMgian
03/06/2020, 8:56 AMgian
03/06/2020, 8:56 AMgian
03/06/2020, 8:59 AMfoo?.bar != null
gian
03/06/2020, 9:03 AMpublic inline fun CharSequence?.isNullOrEmpty(): Boolean {
contract {
returns(false) implies (this@isNullOrEmpty != null)
}
return this == null || this.length == 0
}
Oscar
03/06/2020, 9:09 AMOscar
03/06/2020, 9:11 AM?.
in the expression on which the contract is supposed to work is ruining itOscar
03/06/2020, 9:12 AMfoo?.bar != null
works because you’re not calling any functionOscar
03/06/2020, 9:12 AMdmitriy.novozhilov
03/06/2020, 3:08 PMgian
03/06/2020, 3:09 PM