Search code examples
genericskotlinnullable

kotlin, is it ok to call null.also{}


There is code like:

result.also{......}

but the result might be null and the compiler does not complain, it is same as

null.also{...}

is it ok to call also{} on null?


Solution

  • Yes it is. As the function definition tells you...

    inline fun <T> T.also(block: (T) -> Unit): T (source)
    

    ...T does not define any upper bound and may therefore be used with any, nullable and non-nullable, type (<T> is the same as <T: Any?>).

    If you're afraid about NullPointerExceptions, you don't need to be. The also function simply invokes the block with its receiver, null in your case, before again returning the receiver. For example, the following is legit:

     //returns null and _also_ prints "null"
    return null.also { println(it) }