Use of Boolean? in if expression

前端 未结 11 1861
陌清茗
陌清茗 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条回答
  • 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
      }
    }
    
    0 讨论(0)
  • 2020-12-14 00:11

    For Kotlin what i normally use is

    if (object?.booleanProperty ==true)
       { 
         //do stuff 
       }
    

    this would only work when the property is true and the object is not null. For the reverse:

    if (!object?booleanProperty !=true)
       { 
         //do Stuff
       }
    
    0 讨论(0)
  • 2020-12-14 00:11

    Let's use an if-else statement with an Elvis Operator:

    val a: Boolean?
    val b: Boolean?
    
    a = true
    b = null
    
    if (a != null ?: b) { 
        println("One of them isn't nullable...")
    } else {
        println("Both are nullables!")
    }
    

    // Result: "One of them isn't nullable..."

    a = null
    b = null
    
    if (a != null ?: b) { 
        println("One of them isn't nullable...")
    } else {
        println("Both are nullables!")
    }
    

    // Result: "Both are nullables!"

    0 讨论(0)
  • 2020-12-14 00:13

    It's pretty easy to add an extension function if that helps you.

    fun Boolean?.orDefault(default: Boolean = false): Boolean {
        if (this == null)
            return default
        return this
    }
    
    var x: Boolean? = null
    
    if(x.orDefault()) {
    ..
    }
    
    0 讨论(0)
  • 2020-12-14 00:15

    first, add the custom inline function below:

    inline fun Boolean?.ifTrue(block: Boolean.() -> Unit): Boolean? {
        if (this == true) {
            block()
        }
        return this
    }
    
    inline fun Boolean?.ifFalse(block: Boolean?.() -> Unit): Boolean? {
        if (null == this || !this) {
            block()
        }
    
        return this
    }
    

    then you can write code like this:

    val b: Boolean? = ...
    b.ifTrue {
       /* Do something in true case */
    }
    
    //or
    
    b.ifFalse {
       /* Do something else in false case */
    }
    
    0 讨论(0)
提交回复
热议问题