Use of Boolean? in if expression

前端 未结 11 1895
陌清茗
陌清茗 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: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-> {}
    }
    

提交回复
热议问题