Use of Boolean? in if expression

前端 未结 11 1903
陌清茗
陌清茗 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: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 */
    }
    

提交回复
热议问题