Search code examples
kotlintypechecking

Is it necessary to check null when use 'is' operator


I have an instance which can be null. Fox example

var str: String? = null

So I need to check if str is String. Do I need to check for null if I use the is operator. First option:

if(str is String) {}

Second option:

if(str != null && str is String) {} 

Please help me which way is better to use ?


Solution

  • The is operator is safe and returns false in the case you supply a null instance

    https://pl.kotl.in/HIECwc4Av

    Somewhere, you HAVE to nullcheck. Kotlin provides many ways to enforce non-null:

    Use a non-null type:

    var nonNull : String = ""
    var nullable : String? = "" // notice the ?
    
    nullable = null // works fine!
    nonNull = null // compiler error
    

    and if you encounter a nullable type, you can use let {} ?: run {} construct to unwrap it and execute your code with a non-nullable:

    nullable?.let { // use "it" to access the now non-null value
        print(it)
    } ?: run { // else
        print("I am null! Big Sad!")
    }
    

    Kotlin strictly distinguishes between nullable T? and nonnull T. Use T wherever possible to avoid null checks.