Skip to content
Ameen Abozaid
In reviewJNR-001-L04

Switch expressions and pattern matching

  • Lesson 4 of 8
  • 11 min read
  • Junior
On This Lesson 4 topics

The content for this lesson is written and waiting for review. The outline below shows what it covers. It will be published once it is approved.

In this lesson

handle every case of a sealed type with a switch.

Planned topics

  • A switch expression returns a value and uses ->, with no fall-through.
  • A pattern in a case matches a type and gives it a name: case Percentage p.
  • On a sealed type, the switch must cover all cases or it will not compile.
  • Do not add default: it hides the compile error when you add a new type.
  • instanceof patterns do the same for single checks: if (o instanceof String s).
Draft outline details

Demonstration

java
Money apply(Discount d, Money price) {
    return switch (d) {
        case Percentage p  -> price.minusPercent(p.percent());
        case FixedAmount f -> price.minus(f.amount());
        case BuyXGetY b    -> price; // handled per cart line
    };
}

Check your understanding

Why avoid default on a sealed switch?

Show answer

It stops the compiler from warning you about a new, unhandled type.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.