如何避免&"?. let& quot"嵌套"null check"? [英] How to avoid nest 「null check」by "?.let"?

查看:45
本文介绍了如何避免&"?. let& quot"嵌套"null check"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让Kotlin帮助我避免一些if(null?)doSomething.

let in kotlin help me avoid some if(null?) doSomething.

但是我有一个问题.

A是对象的字段,而B是对象A的字段.它们可以是空包.

A is the field of the object, And B is the field of Object A. they can be nullbale.

他们在这样的代码中.

class Obj {
   var a : A?
}

class A {
   var b : B?
}

我知道我可以通过双重租赁来做到这一点:

I knew I can do it by double let:

A?.let { 
   it.B.let {
      // a must nonnull
   }
}

A?.B?.let {
  // how to use A ,without null check again? 
}

推荐答案

有扩展功能可以实现您所需要的功能,您可以在此线程中找到它们

There are extension functions out there to achieve what you're looking for, you can find them in this thread https://discuss.kotlinlang.org/t/kotlin-null-check-for-multiple-nullable-vars/1946

但是说实话,您最好只使用基本的if检查,如果变量是可变的,则可以先将其分配给 val .

But honestly, you're probably better of just using a basic if check here, if the variable is mutable you can assign it to a val first.

val _a = a
val _b = b
if (_a != null && _b != null) {

}

如果您仍然想使用let,在这种情况下,您可以创建一个配对并使用 takeIf

If you still really want to use let though, for this case you could create a pair and use takeIf

(a to b)
    .takeIf { (a, b) ->
        a != null && b != null
    }
    ?.let { (a, b) ->

    }

但是,编译器不会将值智能广播为非空值,因此您仍然必须对它们执行非空(!!)断言.

However the compiler won't smartcast the values as non-null, so you will still have to perform a non-null (!!) assertion on them.

这篇关于如何避免&"?. let& quot"嵌套"null check"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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