Switch Expressions: Yielding Values
What you'll learn: How to return values from multi-line switch expression blocks using the yield keyword.
Sometimes a single arrow expression isn't enough—you need multiple statements to compute your result. That's where yield comes in.
When Arrow Syntax Isn't Enough
With arrow syntax (->), you can return a value directly if it's a single expression:
int numLetters = switch (day) {
case "Monday", "Friday", "Sunday" -> 6;
case "Tuesday" -> 7;
default -> 9;
};
But what if you need to perform calculations, declare local variables, or use multiple statements before determining the value? Enter yield.
The yield Keyword
Think of yield as a "return for switch expressions." It exits the block and provides the value the switch expression should produce:
int dayLength = switch (day) {
case "Monday", "Friday", "Sunday" -> {
int letters = 6;
yield letters;
}
case "Tuesday" -> {
int letters = 7;
yield letters;
}
default -> {
int letters = 9;
yield letters;
}
};
Notice the curly braces around each case block and the yield statement at the end of each block. Without yield, the compiler wouldn't know what value to return from those blocks.
Key Rules
yieldonly works inside switch expressions (not traditional switch statements)- Every code path in a block must
yielda value - The yielded value must match the expected type of the switch expression
Key Takeaway: Use yield inside curly-brace blocks within switch expressions when you need multiple statements to compute the value—it tells the switch expression what to produce.