100. Using generic records in record patterns
Declaring a generic record for mapping fruit data can be done as follows:
public record FruitRecord<T>(T t, String country) {}
Now, let’s assume a MelonRecord
, which is a fruit (actually, there is some controversy over whether a melon is a fruit or a vegetable, but let’s say that it is a fruit):
public record MelonRecord(String type, float weight) {}
We can declare a FruitRecord<MelonRecord>
as follows:
FruitRecord<MelonRecord> fruit =
new FruitRecord<>(new MelonRecord("Hami", 1000), "China");
This FruitRecord<MelonRecord>
can be used in record patterns with instanceof
:
if (fruit instanceof FruitRecord<MelonRecord>(
MelonRecord melon, String country)) {
System.out.println(melon + " from " + country);
}
Or, in switch
statements/expressions:
switch(fruit) {
case FruitRecord<MelonRecord>(
MelonRecord...