Đoạn code sau in ra gì?
static String classify(Object o) {
return switch (o) {
case Integer i when i > 100 -> "big";
case Integer i -> "int";
case String s when s.isBlank() -> "blank";
case String s -> "str:" + s.length();
default -> "other";
};
}
System.out.println(String.join(",",
classify(150), classify(5), classify(" "), classify("hi"), classify(3.0)));
Xem đáp án và giải thích
Guard when cho phép thêm điều kiện boolean vào một pattern, thay cho chuỗi if lồng bên trong case. Case có guard phải đứng trước case cùng kiểu không guard, nếu không compiler báo lỗi dominance. Biến pattern (i, s) dùng được ngay trong biểu thức when.