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")
equalsfunction is defined as extension function on nullable String referenceString?, whilecontainsmethod is defined on non-nullableCharSequence.In both cases
myStris nullable String, so you cannot callcontainsdirectly. You can use null safety operator?.for callingcontainsPS: In case of equality check, you don't need to use
equalsmethod, instead you can just use==operator