How to use null in switch

前端 未结 12 1084
南方客
南方客 2020-12-04 10:17
Integer i = ...

switch (i){
    case null:
        doSomething0();
        break;    
    }

In the code above I cant use null in switch case state

12条回答
  •  暖寄归人
    2020-12-04 11:05

    Some libraries attempt to offer alternatives to the builtin java switch statement. Vavr is one of them, they generalize it to pattern matching.

    Here is an example from their documentation:

    String s = Match(i).of(
        Case($(1), "one"),
        Case($(2), "two"),
        Case($(), "?")
    );
    

    You can use any predicate, but they offer many of them out of the box, and $(null) is perfectly legal. I find this a more elegant solution than the alternatives, but this requires java8 and a dependency on the vavr library...

提交回复
热议问题