38

JDK 12 – JEP 325 Switch Expressions

 5 years ago
source link: https://www.tuicool.com/articles/hit/faq6J3E
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JDK 12 went GA on March 19, 2019, keeping its word on shorter release cycles and frequent releases. The features part of the release can be found here . One of the interesting features for developers is the “ JEP 325 Switch Expressions ,” which is available as a preview feature.

A preview feature, as defined here , is:

"A preview language or VM feature is a new feature of the Java SE Platform that is fully specified, fully implemented, and yet impermanent. It is available in a JDK feature release to provoke developer feedback based on real world use; this may lead to it becoming permanent in a future Java SE Platform."

In this article, I will show you how switch has evolved from being a statement to an expression. A statement is something that executes but doesn’t evaluate to some value, whereas expression is something that, on execution, evaluates to a value:

//Statement
System.out.println("This is a statement");

//Expression
6 + 5;

Switch as Expressions

The syntax for switch as an expression has changed:

Object switchResult = switch ( variable ) {
    case choice1 -> result1;
    case choice2 -> result2;
    default -> resultDefault;
}

In addition to the above use of a switch, it can be used as a statement as well:

switch( variable ) {
    case choice1: 
      doSomeThing(); 
      break;
    case choice2:
      doOtherThing();
      break;
    default:
      doDefaultThing();
}

I am not going into the motivation for introducing the switch expressions. You can read about it here . The remaining part of the article will demonstrate how the switch can be used as an expression. The following code snippet shows the use of switch as an expression. Be sure to observe that switch now is yielding a value, which, in this case, is boolean :

public static boolean isHealthy(String food){
    return switch (food){
        case "Fruit"  -> true;
        case "Vegetable" -> true;
        case "Pizza" -> false;
        case "Burger" -> false;
        case "Pulses" -> true;
        case "Soft Drink" -> false;
        default -> false;
    };
}

System.out.printf("Fruit is %s\n" , isHealthy("Fruit"));

From the code snippet above, we can see that the expression used in the switch can now be a string as well. This is applicable for both in the statement and the expression.

If the possibility of the values of the expression being evaluated is not a fixed set, then we need to provide the default block. If we are using an enum as switch expression, then we don’t need to provide a default case because the possible outcomes in the enum are limited to the enum values. This is shown in the example below:

enum Food {
    Fruit, Vegetable, Pizza, Burger, Pulses, Soft_Drink
}

public static boolean isHealthEnumVersion(Food food){
    return switch (food){
        case Fruit -> true;
        case Vegetable -> true;
        case Pizza -> false;
        case Burger -> false;
        case Pulses -> true;
        case Soft_Drink -> false;
    };
}

System.out.printf("Pizze is %s\n", isHealthEnumVersion(Food.Pizza));

Another example where we put the result of method evaluation as an expression in the switch:

public static int evaluateLunch(Food food){
    return switch (isHealthEnumVersion(food).toString()){
        case "true" -> 10;
        case "false" -> 5;
        default -> 0;
    };
}

System.out.printf("Your food received %d points\n",
        evaluateLunch(Food.Burger));

Block of Code as Case Evaluation

In the previous examples, we saw the case mapped against single line expressions. How do we deal with when we need a block of code to be evaluated for the case?

public static PreparedFood prepareFood(Food food){
    return switch (food){
        case Pizza -> {
            System.out.println("doing pizza related operations");
            break new PreparedFood(food);
        }
        case Burger -> {
            System.out.println("Doing burger related operations ");
            break new PreparedFood(food);
        }
        default -> {
            System.out.printf("Doing %s related operations\n",
               food.toString());
            break new PreparedFood(food);
        }
    };

}

You can notice that the break has been enhanced to accept a parameter, which becomes the result of the evaluation of the code block against the case.

Switch as an Expression Using the Old Syntax

We can stick to the old syntax of switch i.e without the -> symbol, as shown below:

public static int evaluateLunchOldWay(Food food){
    return switch (isHealthEnumVersion(food).toString()){
        case "true": break 10;
        case "false":  break 5;
        default: break 0;
    };
}

The complete code for this article can be found here .


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK