在执行IF块之前测试对象成员是否为null [英] Test object member for null before executing IF block

查看:60
本文介绍了在执行IF块之前测试对象成员是否为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

class Countries {
    var list: MutableList<String>? = null
}

val countries = Countries()

if (countries.list!!.isNotEmpty()) {

}

在运行时,这将引发异常,因为list为null.我可以改为:

At runtime this will raise an exception because list is null. I can do this instead:

if ((countries.list != null) && countries.list!!.isNotEmpty()) {

}

如果我有一个名为areInitialized的布尔成员,该布尔成员可以为空,那么我可以创建一个像这样的infix函数:

If I had a boolean member called areInitialized that was nullable, I could create a infix function like this:

infix fun Any?.ifTrue(block: () -> Unit) {
    if ((this != null) && this == true) block()
}

然后像这样使用它:

countries.areInitialized ifTrue {

}

但是我似乎无法为可变列表创建类似的内容.

But I can't seem to create something similar for a mutable list.

但是我讨厌不得不在代码的其他部分的成员字段上重复此测试以使null为空. Kotlin中有更简单的方法可以做到这一点吗?

But I hate having to repeat this test for null on an member field in other parts of code. Is there a simpler way in Kotlin to do this?

推荐答案

我会尽可能地坚持标准.因此,在您的示例中,我不会介绍该ifTrue函数,而是使用 takeIf takeUnless 安全运算符?.结合使用代替,例如:

I would try to stick to the standard as often as you can. So in your example I wouldn't have introduced that ifTrue-function, but rather used takeIf or takeUnless in combination with the safe operator ?. instead, e.g.:

countries?.takeIf { it.areInitialized == true }
         ?.also { 
             /* do something with countries */ 
         }

或者,如果必须返回一个值,则将alsolet交换(或查看其他

Or if you must return a value, exchange also with let (or see the other scope functions).

然后,同样适用于countries中的列表:

The same then also works for the list within countries:

countries?.takeUnless { it.list.isNullOrEmpty() }
         ?.also { 
             /* do something with countries */ 
             it.list!!.forEach(::println)
         }

这篇关于在执行IF块之前测试对象成员是否为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆