marp: true title: Una mirada funciona a Java 21 theme: gaia footer: #Commitconf 2024 color: #fff transition: fade-out
Antonio Muñoz
switch
.var value = switch (input) { case "a" -> 1; case "b" -> 2; default -> 0; };
public record Movie(String title, int year, int duration) { }
public sealed interface Shape { record Square(int side) implements Shape {} record Rectangle(int weight, int height) implements Shape {} record Circle(int radious) implements Shape {} }
var result = switch (obj) { case Integer i -> String.format("int %d", i); case Long l -> String.format("long %d", l); case Double d -> String.format("double %f", d); case String s -> String.format("String %s", s); default -> obj.toString(); };
var area = switch (this) { case Square(var side) -> side * side; case Rectangle(var weight, var height) -> weight * height; case Circle(var radious) -> Math.PI * Math.pow(radious, 2); };
record
es un producto de tipos.sealed interface
es una suma de tipos.public sealed interface Tree { record Node(String value, Tree left, Tree right) implements Tree { } record Leaf(String value) implements Tree {} }
Optional
con ADTspublic sealed interface Optional<T> { record Empty<T>() implements Optional<T> { } record Present<T>(T value) implements Optional<T> {} }
Json
con ADTspublic sealed interface Json { enum JsonNull implements Json { NULL } enum JsonBoolean implements Json { TRUE, FALSE } record JsonString(String value) implements Json {} record JsonNumber(Number value) implements Json {} record JsonObject(Map<String, Json> value) implements Json {} record JsonArray(List<Json> value) implements Json {} }
var result = switch (obj) { case Integer _ -> "int"; case Long _ -> "long"; case Double _ -> "double"; case String _ -> "string"; default -> "other"; };
var result = switch (obj) { case int i -> String.format("int %d", i); case long l -> String.format("long %d", l); case double d -> String.format("double %f", d); case String s -> String.format("String %s", s); default -> obj.toString(); };
Point newPoint = oldPoint with { x *= 2; y *= 2; };