简体   繁体   English

如何在Android Activity上使用Kotlin扩展功能正确执行空检查

[英]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. 我是Kotlin的新手,正在尝试将现有代码库中的许多Android Util方法之一转换为Kotlin扩展函数。

This is the Kotlin code: 这是Kotlin代码:

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

Which is meant to be the equivalent of this Java method: 这等效于此Java方法:

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 . 但是,只要Activitynull ,我仍然会在Kotlin代码中获得NPEs Any thoughts on where I'm going wrong? 对我要去哪里错有任何想法吗?

I suppose you get NPE not in the isAlive() function but somewhere after, when the Activity is referenced. isAlive()引用Activity时,您不是在isAlive()函数中而是在之后的某个地方获取了NPE。 This is likely caused by the fact that .isAlive() returns true on null receiver. 这可能是由于.isAlive()null接收器上返回true的事实引起的。

That's because if the receiver is null , this?.isFinishing ?: false chooses the right branch false , thus !(this?.isFinishing ?: false) is true . 这是因为,如果接收者为nullthis?.isFinishing ?: false选择右分支false ,因此!(this?.isFinishing ?: false)true

Try changing your function in either way so that it returns false on null receiver, for example: 尝试以任何一种方式更改函数,以使其在null接收器上返回false ,例如:

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

I would suggest writing 我建议写

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

I find the separate null check and condition easier to read than the combined versions. 我发现单独的null检查和条件比合并的版本更易于阅读。

虽然可接受的答案很好用,但我建议改用相等检查,因为这样会导致可读性更高的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM