Java 17:模式匹配的切换
发布者::Fahd Shariff inCore Java September 28th, 2021 0 Views
在Java 17中(几天前才发布),switch的模式匹配作为一个预览语言功能被引入,它允许用模式而不仅仅是常量进行案例标签。下面是一个例子,展示了如何在类型模式上进行匹配:
public static String typedPatternMatching(Object o) {
return switch(o) {
case null -> "I am null";
case String s -> "I am a String. My value is " + s;
case Integer i -> "I am an int. My value is " + i;
default -> "I am of an unknown type. My value is " + o.toString();
};
}
// Output:
> typedPatternMatching("HELLO")
"I am a String. My value is HELLO"
> typedPatternMatching(123)
"I am an int. My value is 123"
> typedPatternMatching(null)
"I am null"
> typedPatternMatching(0.5)
"I am of an unknown type. My value is 0.5"
你也可以使用守护模式,以细化模式,使其只在某些条件下匹配,例如:
public static String guardedPattern(Collection<String> coll) {
return switch(coll) {
case List list && (list.size() > 10) ->
"I am a big List. My size is " + list.size();
case List list ->
"I am a small List. My size is " + list.size();
default ->
"Unsupported collection: " + coll.getClass();
};
}
如果你有一个Sealed Class(在Java 17中成为永久的语言特性),编译器可以验证switch语句是否完整,所以不需要default 标签,比如说:
sealed interface Vehicle permits Car, Truck, Motorcycle {}
final class Car implements Vehicle {}
final class Truck implements Vehicle {}
final class Motorcycle implements Vehicle {}
public static String sealedClass(Vehicle v) {
return switch(v) {
case Car c -> "I am a car";
case Truck t -> "I am a truck";
case Motorcycle m -> "I am a motorcycle";
};
}