Record patterns
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
switchand ininstanceof. - 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
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.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.