Use of Boolean? in if expression

前端 未结 11 1894
陌清茗
陌清茗 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: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()) {
    ..
    }
    

提交回复
热议问题