Skip to content

Commit

Permalink
dynamic_binding.md: add snippet on record patterns
Browse files Browse the repository at this point in the history
  • Loading branch information
btj authored Dec 1, 2023
1 parent 550e233 commit e3b764f
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions dynamic_binding.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,4 +233,16 @@ public record Circle(int x, int y, int radius) {
}
}
```

Instances of record classes can be inspected concisely using *record patterns*: the snippet
```java
if (shape instanceof Circle circle)
return "Circle(" + circle.x + ", " + circle.y + ", " + circle.radius + ")";
```
can be written more concisely as
```java
if (shape instanceof Circle(int x, int y, int radius))
return "Circle(" + x + ", " + y + ", " + radius + ")";
```

Warning: be careful when using a record class if some of the components are mutable objects that should be treated like representation objects; the predefined members do not prevent representation exposure. Be extra careful when using arrays as record components: an array's `equals` method simply compares the identities of the two objects; it does not compare the array elements.

0 comments on commit e3b764f

Please sign in to comment.