Why can't I use switch statement on a String?

前端 未结 16 2067
面向向阳花
面向向阳花 2020-11-21 07:57

Is this functionality going to be put into a later Java version?

Can someone explain why I can\'t do this, as in, the technical way Java\'s switch state

16条回答
  •  猫巷女王i
    2020-11-21 08:08

    JEP 354: Switch Expressions (Preview) in JDK-13 and JEP 361: Switch Expressions (Standard) in JDK-14 will extend the switch statement so it can be used as an expression.

    Now you can:

    • directly assign variable from switch expression,
    • use new form of switch label (case L ->):

      The code to the right of a "case L ->" switch label is restricted to be an expression, a block, or (for convenience) a throw statement.

    • use multiple constants per case, separated by commas,
    • and also there are no more value breaks:

      To yield a value from a switch expression, the break with value statement is dropped in favor of a yield statement.

    So the demo from the answers (1, 2) might look like this:

      public static void main(String[] args) {
        switch (args[0]) {
          case "Monday", "Tuesday", "Wednesday" ->  System.out.println("boring");
          case "Thursday" -> System.out.println("getting better");
          case "Friday", "Saturday", "Sunday" -> System.out.println("much better");
        }
    

提交回复
热议问题