CASE 1: it can compile and run. why no exception when null call equals() ?
var myStr:String? = null
if (myStr.equals("hello"))
println("equals hello")
else
println("not equals hello")
CASE 2: it cannot compile. I suppose it is similar to the above case, but I am wrong. Why?
var myStr:String? = null
if (myStr.contains("hello"))
println("contains hello")
else
println("not contains hello")
equals
function is defined as extension function on nullable String referenceString?
, whilecontains
method is defined on non-nullableCharSequence
.In both cases
myStr
is nullable String, so you cannot callcontains
directly. You can use null safety operator?.
for callingcontains
PS: In case of equality check, you don't need to use
equals
method, instead you can just use==
operator