21 Mart 2022 Pazartesi

Pattern match for switch - Java 17 İle Geliyor

Giriş
Açıklaması şöyle. Burada switch expressions kısmı önemli. Yani "switch block" ve "switch expression" farklı şeyler. Switch Expressions yazısına bakabilirsiniz.
The final new language feature that was added to Java 17 is pattern matching for switch expressions. Note that this is a preview version. This is the second occurrence of pattern matching in the language after it has been introduced via the instanceof operator.

In its most simple form, pattern matching is performed on the type of variable that is supplied. Compare this to a classical switch expression/statement where the value is used. Also note that there is a special handling for the null values. Normally, a null value would lead to a NullPointerException (NPE) so it would require an additional check. Thanks to the special handling of the null value this is no longer required. Finally, also notice that the required casting is again performed automatically by the compiler.
1. Genel Kullanım
Örnek

Şöyle yaparız
String printValue(Object obj) {
  return switch (obj) {
    case Integer i -> String.format("It is an integer with value %d", i);
    case Long l -> String.format("It is a Long with value %d", l);
    case String s -> String.format("It is a String with value %s", s);
    case null -> new String("You can't pass in a null value!");
    default -> String.format("Dunno the type, but the value is %s", obj.toString());
  };
}
2. Guarded Pattern
Örnek
Şöyle yaparız
String printValue(Object obj) {
return switch (obj) { case null -> new String("You can't pass in a null value!"); case String s && s.length() > 10 -> String.format("Long String with value %s", s); case String s -> String.format("Not so long String with value %s", s); default -> String.format("Dunno the type, but the value is %s", obj.toString()); }; }
Açıklaması şöyle
In the example above, a distinction can be made between strings with a length of up to 10 characters and strings with more than 10 characters.
Örnek
Şöyle yaparız
return switch (obj) {
case Integer i -> "It is an integer"; case String s -> "It is a string"; case Employee employee && employee.getDept().equals("IT") -> "IT Employee"; default -> "It is none of the known data types"; };
3. Parenthesised pattern
Açıklaması şöyle
Basically, this is when you use additional parenthesis to prevent an invalid outcome of a pattern predicate
Örnek
Şöyle yaparız
boolean printValue(Object obj) {
return switch (obj) { case String s && s.length() >= 2 && (s.contains("@") || s.contains("!")) -> true; default -> false; }; }


Hiç yorum yok:

Yorum Gönder