class Shape permits Circle, Rectangle, Square {...} Shape rotate(Shape shape, double angle) { return switch (shape) { case Circle c -> c; // no action needed case Rectangle r -> r.rotate(angle); case Square s -> s.rotate(angle); } }
if (o instanceof String s) { System.out.println(s.length()); } Object o = "test"; if (o instanceof String) { String s = (String) o; System.out.println(s.length()); }
レコードの分解 switch (obj) { case String s -> parseInt(s); case Integer i -> i; default -> 0; } switch (obj) { case Add(int l, int r) -> l + r; // record Add(int l, int r) case Sub(int l, int r) -> l - r; // record Sub(int l, int r) case Num(int i) -> i; // record Num(int i) default -> throw new UnsupportedOparation(); }
null; println(s.length()); Exception in thread "main" java.lang.NullPointerException at Sample.main(mysample.java:4) String s = null; println(s.length()); Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "Sample.s" is null at Sample.main(mysample.java:4)