Ma Guarded patterns a destructuring (aspon ve switch):
record Person(String firstname, String surname) {}
record Couple(Person p1, Person p2) {}
public static void main(String[] args) {
Person daddy = new Person("John", "Doe");
Person mommy = new Person("Jane", "Doe");
Person uncle = new Person("John", "Apples");
var objects = Arrays.asList(
new Couple(daddy, mommy),
new Couple(mommy, daddy),
new Couple(uncle, daddy),
10,
"Random string");
objects.stream()
.map(i -> switch (i) {
case Couple(Person p1, Person p2)
when p1.firstname.equals(p2.firstname) -> (Supplier<String>) () -> "Split it in half between " + p1 + " and " + p2;
case Couple c
when c.p1.firstname.equals("John") -> (Supplier<String>) () -> "Daddy is paying";
case Couple c
when c.p1.firstname.equals("Jane") -> (Supplier<String>) () -> "Mommy is paying";
case Integer ignored -> (Supplier<String>) () -> "What are you doing here Integer";
case Object ignored -> (Supplier<String>) () -> "Runners... call 911";
})
.forEach(i -> System.out.println(i.get()));
}
No.. slušelo by se říct, že je to "preview feature" v nejnovější JDK 19 (tj. běžně se to zatím použít nedá a možná to nakonec ani nebude vypadat takhle) a funguje to jenom na recordy a jen ve switchi (což jsi teda napsal) - ve srovnání s tím, co umí třeba jenom Scala, je to stále úsměvný. Btw vůbec nechápu, proč je tam ten Supplier, zbytečně to ten příklad komplikuje, proč to neni jenom
objects.stream()
.map(it -> switch (it) {
case Couple(Person p1, Person p2)
when p1.firstname.equals(p2.firstname) -> "Split it in half between " + p1 + " and " + p2;
case Couple c
when c.p1.firstname.equals("John") -> "Daddy is paying";
case Couple c
when c.p1.firstname.equals("Jane") -> "Mommy is paying";
case Integer ignored -> "What are you doing here Integer";
case Object ignored -> "Runners... call 911";
})
.forEach(it -> System.out.println(it));