Use of Boolean? in if expression

前端 未结 11 1860
陌清茗
陌清茗 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-13 23:52

    In case if you want to perform operations alike contain on a String you could use equality check like below -

    if (url?.contains("xxx") == true){
      return false;
    }
    
    0 讨论(0)
  • 2020-12-13 23:56

    If you want to cleanly check whether a Boolean? is true or false you can do:

    when(b) {
        true -> {}
        false -> {}
    }
    

    If you want to check if it's null you can add that (or else) as a value in the when:

    when(b) {
        true -> {}
        false -> {}
        null -> {}
    }
    
    when(b) {
        true -> {}
        false -> {}
        else-> {}
    }
    
    0 讨论(0)
  • 2020-12-13 23:59

    In Kotlin, you can do like this:

    val b: Boolean? = true
    if (b == true) { // if b is null, this should be null == true
        /* Do something */
    } else {
        /* Do something else */
    }
    
    0 讨论(0)
  • 2020-12-14 00:01

    You can do with safe Operator "let"

    val b: Boolean? = null
    b?.let { flag ->
        if(flag){
            // true Block
        } else {
            // false Block
        }
    }
    
    0 讨论(0)
  • 2020-12-14 00:07

    Kotlin will statically analyze your null checks. This is fine:

    val b: Boolean? = null
    if (b != null && b) {
        println(b)
    }
    

    Even though this fails with type error:

    val b: Boolean? = null
    if (b == null && b) {
        println(b)
    }
    

    For more see: http://kotlinlang.org/docs/reference/null-safety.html

    You can also use "null coalescing operator" (which will work for mutable variables):

    val b: Boolean? = null
    if (b ?: false) {
        println(b)
    }
    
    0 讨论(0)
  • 2020-12-14 00:08

    You can compare nullable boolean with true, false or null using equality operator:

    var b: Boolean? = null
    if (b == true) {
        // b was not null and equal true
    } 
    if (b == false) {
       // b is false 
    }
    if (b != true) { 
       // b is null or false 
    }
    
    0 讨论(0)
提交回复
热议问题