Skip to content
Ameen Abozaid
In reviewJNR-001-L05

Record patterns

  • Lesson 5 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

take a record apart directly in a pattern.

Planned topics

  • A record pattern pulls out the components: case Percentage(int percent).
  • It works in switch and in instanceof.
  • Patterns can be nested, for example a record inside a record.
  • Use it when you only need the parts, not the whole object.
  • Stop nesting when the line becomes hard to read.
Draft outline details

Demonstration

java
return switch (d) {
    case Percentage(int percent) -> price.minusPercent(percent);
    case FixedAmount(Money amount) -> price.minus(amount);
    case BuyXGetY(int buy, int free) -> price;
};

Check your understanding

What is the benefit of case Percentage(int percent) over case Percentage p?

Show answer

You get the value directly, without calling p.percent().

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.