kotlinnullnullsafe

How to use equals() and contains() to check nullable type of data? I suppose they are both string's methods, but why they behave differently?


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")

Solution

  • equals function is defined as extension function on nullable String reference String?, while contains method is defined on non-nullable CharSequence.

    public actual fun String?.equals(other: String?, ignoreCase: Boolean = false): Boolean = ...
    
    
    public operator fun CharSequence.contains(other: CharSequence, ignoreCase: Boolean = false): Boolean = ...
    

    In both cases myStr is nullable String, so you cannot call contains directly. You can use null safety operator ?. for calling contains

    if(myStr?.contains("hello") == true)
        println("contains hello")
    else
        println("not contains hello")
    

    PS: In case of equality check, you don't need to use equals method, instead you can just use == operator