Record patterns and null components
A record pattern like Point(int x, int y) checks that a value is a Point and pulls out its components into variables in one step. Record patterns nest, so Line(Point(var x1, var y1), Point p2) matches and unpacks a whole tree of records at once, in instanceof and in switch.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
With record Point(int x, int y) and record Line(Point from, Point to), write kind(Line) returning "a single point", "horizontal", "vertical", "diagonal" (45 degrees) or "sloped", using nested record patterns and guards.
Model a binary tree as sealed interface Tree permits Leaf, Node with record Leaf() and record Node(Tree left, int value, Tree right). Write sum, height and isLeafNode (a node whose children are both leaves) with record patterns.
Model a café bill: sealed interface Item permits Food, Drink, Food(String name, int pricePaise), Drink(String name, int pricePaise, boolean large), and Line(Item item, int qty). Large drinks cost 1000 paise more; 3 or more of the same food get 10% off. Write total(Line) with nested patterns and print a bill.
Explain it without notes
What does o instanceof Point(int x, int y) do, step by step?
How do record patterns behave with null, both for the record and for its components?
How does the compiler check exhaustiveness for nested record patterns over sealed types?
Why can't you write a record pattern for an ordinary class?
What is the relationship between records, sealed interfaces and record patterns?
Expected output
box of text: tea
box of number: 5
box of something else: 2.5
box of something else: null
no box
not a box
Box(String s) matches Box(null)? false
Box(Object x) matches Box(null)? true
Box(var v) matches Box(null)? true
Box(var v) matches null? false