RUVIDEO
Поделитесь видео 🙏

[1min] Java 18 for developers

Pattern Matching for Switch (2nd Preview) #java #java18 #developer
JEP 420 - Project Amber
Enhance Java programming language with pattern matching for switch expressions and statements, along with extensions to the language of patterns.
(?Remember preview features are not enabled by default, enable it like this )

Let's take an example for Pattern matching for switch
Before:
It works on few types: numeric, Enums and Strings.
To check a pattern, you needed to use a chain of if/else statements like below???
static String formatter(Object o) {
String formatted = "unknown";
if (o instanceof Integer i) {
formatted = String.format("int %d", i);
} else if (o instanceof Long l) {
formatted = String.format("long %d", l);
} else if (o instanceof Double d) {
formatted = String.format("double %f", d);
} else if (o instanceof String s) {
formatted = String.format("String %s", s);
}
return formatted;
}


After:
Using pattern matching however, makes it more clearer???

static String formatterPatternSwitch(Object o) {
return switch (o) {
case Integer i arrow String.format("int %d", i);
case Long l arrow String.format("long %d", l);
case Double d arrow String.format("double %f", d);
case String s arrow String.format("String %s", s);
default arrow o.toString();
} ;
}


Above all, this code is optimizable by the compiler.
Remember the case statements have to be exhaustive, so you would want to use a default value at the end.
If you use Sealed classes, you would not use a default value, as your labels cover all of the cases.
Something to highlight is the null value handling:
Now you can integrate the null case in the switch, making the code easier to read and maintain???

static String formatterPatternSwitch(Object o) {
return switch (o) {
case null arrow "null";
case Integer i arrow String.format("int %d", i);
case Long l arrow String.format("long %d", l);
case Double d arrow String.format("double %f", d);
case String s arrow String.format("String %s", s);
default arrow o.toString();
} ;
}





Pattern matching for switch - Guarded patterns
Before:
After a successful pattern match, we often need for the test which can lead for cumbersome code like this one below???(The desired test: if o is String of length 0 is split between case and if statement)

static void test(Object o) {
switch (o) {
case String s:
if (s.length() == 1) {...}
else {...}
break;
...
};
}


?You have a switch statement and a if right inside.
After:
We can improve the readability if the pattern supports the combination of pattern and boolean expression.
So, that's what we have below: (First case matches for string of length 1, second case matches of other lengths)???

static void test(Object o) {
switch (o) {
case String s && (s.length() == 1)arrow ...
case String s arrow ..
...
};
}


Guarded pattern allow us to write it in a more clearer way.


Pattern matching for switch - Possible issues
There are a couple of new gotchas that could arise with pattern matching for switch.
Dominance of pattern labels:
It is a compile-time error if a pattern label in a switch block is dominated by an earlier pattern.
It is possible an expression match multiple labels in a switch block. This is allowed, but they must be pleased in the right order??? (Error- pattern is dominated by previous pattern)

switch (o) {
case String s arrow ...
case String s && (s.length() 1) arrow ...
...
};


The second label can never be reached, it is dominated by an earlier case, this would result in a compile-time error.
No fall through allowed when declaring a pattern variable:
In the example below, if the variable is a character, we would go ahead and print character.
But as there is no break statements, execution would flow to the next label.
But since the variable "i" has not been declared, it has not been initialized, we would get an error.
It is therefore a compile-time error to allow fall-through to a case that declares a pattern.
Fall-through for a case that does not declare a pattern is fine.

switch (o) {
case Character c:
System.out.println("character");
case Integer i: //Error. Can't fall through!
System.out.println("An integer " + i);
...
}

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «[1min] Java 18 for developers», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.