Use of Boolean? in if expression

前端 未结 11 1897
陌清茗
陌清茗 2020-12-13 23:14

If I have a nullable Boolean b, I can do the following comparison in Java:

Boolean b = ...;
if (b != null && b) {
   /* Do something */
         


        
11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 00:09

    From what I've seen the Boolean? is a result of a method that returns Boolean on an object that is nullable

    val person: Person? = null
    ....
    if(person?.isHome()) { //This won't compile because the result is Boolean?
      //Do something
    }
    

    The solution I've been using is to use the let function to remove the possible returned null value like so

    person?.let {
      if(it.isHome()) {
        //Do something
      }
    }
    

提交回复
热议问题