Sage-Code Laboratory
index<--

Switch Expressions

Switch expressions are similar to switch statement. Instead of imperative syntax is using an alternative syntax that can return a value just like a function.

The advantage of switch expressions is to simplify syntax for making compact expressions. It is a variation of ternary operator "?" that is used in C and C++

Switch expressions has 2 alternative syntax. One is called "Case L ->", the other is called "Case L :". You can use symbol "->" or "yield" to return a value.

Case ":" (imperative)

Next syntax pattern is classic, it was available before JDK-8 and is yet available. This pattern can't be used in expressions. It is an imperative statement.

switch (variable) {
    case value1: //fall through
    case value2:
        result = result1;
        break;   //stop evaluation
    case value3:
        result = result2;
        break;   //stop evaluation
    ...
    default:
        result = resultN;
}

Case L -> (functional)

Using the new expression syntax require symbol "->" follow by an expression. This form do not allow fall-through but enable a list of values to be used for one or more cases.

result = switch (variable) {
    case value1, value2 -> result1;
    case value3         -> result2;
    ...
    default             -> resultN;
}

Case L ":" (functional)

Using this expression syntax require symbol ":" follow by a block of code and keyword "yield". This syntax require "yield" and do not use break.

result = switch (variable) {
    case value1, value2: { 
        ...
        yield result1; 
    }
    case value3: { 
        ...
        yield result2; 
    }
    ...
    default: { 
        ...
        yield resultX; 
    }
}

Note: Usually a switch expression or statement is used with an enumeration type. Don't warry, if the compiler do not like your switch statement it will complain. If you find yourself in trable you should read more in Oracle documentation.

External Article: Switch Expressions


Read next: Record Classes