In the first example, myStr.equals
calls the String?.equals
extension function, which does the following:
if (this === null)
return other === null
In your case, this
is null
, and other
is not null
, so other === null
produces false
.
In the second example, myStr.contains("hello")
is trying to call a function called contains
, but it doesn't exist, because you have a nullable String?
, and there is no contains
function defined for that type. There is the CharSequence.contains
function, but that is only defined for non-nullable types.
So because the function doesn't exist, you get a compiler error.
Generally, you don't need to use the equals
function anyway, and should prefer the ==
operator:
val myStr:String? = null
if (myStr == "hello")
println("equals hello")
else
println("not equals hello")
For contains, you can use the ?.
operator to ensure the object on the left is not null first:
val myStr:String? = null
if (myStr?.contains("hello") == true)
println("contains hello")
else
println("not contains hello")
Here, myStr?.contains("hello")
produces null
, and null == true
is false
, so the result is false
.