Henrique Henrique - 1 month ago 10
Java Question

How to properly do null checks using Kotlin extension functions on an Android Activity

I'm new to Kotlin and trying to convert one of the many Android Util methods we have in our existing codebase into a Kotlin extension function.

This is the Kotlin code:

fun Activity?.isAlive(): Boolean {
return !(this?.isFinishing ?: false)
}


Which is meant to be the equivalent of this Java method:

public static boolean isAlive(Activity activity) {
return activity != null && !activity.isFinishing();
}


However, I'm still getting
NPEs
in the Kotlin code whenever an
Activity
is
null
. Any thoughts on where I'm going wrong?

Answer

I suppose you get NPE not in the isAlive() function but somewhere after, when the Activity is referenced. This is likely caused by the fact that .isAlive() returns true on null receiver.

That's because if the receiver is null, this?.isFinishing ?: false chooses the right branch false, thus !(this?.isFinishing ?: false) is true.

Try changing your function in either way so that it returns false on null receiver, for example:

fun Activity?.isAlive(): Boolean = !(this?.isFinishing ?: true)