You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SwitchPatternPreview2OK.java 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import java.util.List;
  2. /**
  3. * Inspired by examples in https://openjdk.java.net/jeps/420
  4. */
  5. public class SwitchPatternPreview2OK {
  6. public static void main(String[] args) {
  7. constantLabelMustAppearBeforePattern(-1);
  8. constantLabelMustAppearBeforePattern(0);
  9. constantLabelMustAppearBeforePattern(42);
  10. constantLabelMustAppearBeforePattern(-99);
  11. constantLabelMustAppearBeforePattern(Integer.valueOf(123));
  12. constantLabelMustAppearBeforePattern(null);
  13. System.out.println(testGenericSealedExhaustive(new B<Integer>()));
  14. }
  15. static String constantLabelMustAppearBeforePattern(Object o) {
  16. switch (o) {
  17. case -1, 1 -> System.out.println("special case:" + o);
  18. case Integer i && i > 0 -> System.out.println("positive integer: " + o);
  19. case Integer i -> System.out.println("other integer: " + o);
  20. default -> System.out.println("non-integer: " + o);
  21. }
  22. return o.toString();
  23. }
  24. sealed interface I<T> permits A, B {}
  25. final static class A<X> implements I<String> {}
  26. final static class B<Y> implements I<Y> {}
  27. static int testGenericSealedExhaustive(I<Integer> i) {
  28. return switch (i) {
  29. // Exhaustive as no A case possible!
  30. case B<Integer> bi -> 42;
  31. };
  32. }
  33. }