Newer
Older
commitconf24 / slides.md
@Antonio Muñoz Antonio Muñoz on 28 Mar 2024 9 KB updated

marp: true title: Una mirada funciona a Java 21 theme: gaia footer: #commitconf 2024 author: Antonio Muñoz color: #fff transition: fade-out

backgroundImage: url('https://cdn.wallpapersafari.com/97/99/MnWulT.jpg')

Una mirada :eyes: funcional a Java :two::one:

Antonio Muñoz


¿Quien soy?


Encuesta

  • Java 21? :thumbsup:
  • Java 17? :ok:
  • Java 11? :warning:
  • Todavía Java 8? :cry:
  • Y anteriores a Java 8? :exploding_head:

Jetbrains ecosystem survey

Version Percentage
Java8 50%
Java17 45%
Java11 38%
Java20 11%

Java 8

  • Lanzado en 2014 :rocket:

Agenda :calendar:

  • El largo camino a Java 21.
  • Tipos de datos algebraicos.
  • Futuro.

Java Release Cadence :coffee:

  • Dos release al año.
  • Preview features.
  • They have a plan.

Switch expressions

var value = switch (input) {
    case "a" -> 1;
    case "b" -> 2;
    default -> 0;
};
  • Incluido en Java 14.
  • Una nueva vida para switch.
  • Una gran mejora en general para el lenguage.

Records

public record Movie(String title, int year, int duration) {

}
  • Incluido en Java 16.
  • Muy esperado por la comunidad.
  • Inmutables.
  • Constructor canónico.

Sealed classes and interfaces

public sealed interface Shape {

    record Square(int side) implements Shape {}
    record Rectangle(int weight, int height) implements Shape {}
    record Circle(int radious) implements Shape {}

}
  • Incluido en Java 17.
  • Jerarquías de clases cerradas.

Pattern matching for switch

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();
};
  • Incluido en Java 21.
  • Exhaustiveness.

Record patterns

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);
};
  • Incluido en Java 21.
  • Deconstructores, nos permite acceder a los componentes de los objectos.

Tipos de datos algebraicos

  • AKA ADTs (algebraic data types).
  • Viene de las matemáticas.
  • Productos y sumas de tipos. a + b a * b
  • Cardinalidad.
  • Recursivo.

ADTs

  • Tienen propiedades algebraicas:
    • Identidad: a + 0 <=> a a * 1 <=> a
    • Distributiva: (a * b) + (a * c) <=> a * (b + c)
    • Conmutativa: a * b <=> b * a a + b <=> b + a
    • Asociativa: a + b + c <=> a + (b + c) a * b * c <=> a * (b * c)

ADTs

  • ¿Cómo podemos representarlos en Java?
  • Un record es un producto de tipos.
  • Un sealed interface es una suma de tipos.
  • ¿Pero eso para qué me sirve?

ADTs: Identidad Suma

sealed interface Sum {
    record A(String value) implements Sum {}
    // uninstantiable, similar to Void type
    final class B implements Sum {
        private B() {}
    }
}

ADTs: Identidad Producto

// just one value
enum Unit { VALUE }
record Product(String value, Unit unit) {}

ADTs: List

sealed interface List<T> {

    record NonEmpty<T>(T head, List<T> tail) implements List<T> {}

    record Empty<T>() implements List<T> {}
}

ADTs: Tree

sealed interface Tree<T> {

    record Node<T>(T value, Tree<T> left, Tree<T> right) implements Tree<T> { }

    record Leaf<T>(T value) implements Tree<T> {}
}

ADTs: Optional

sealed interface Optional<T> {

    record Empty<T>() implements Optional<T> { }

    record Present<T>(T value) implements Optional<T> {}
}

ADTs: Either

sealed interface Either<L, R> {

    record Left<L, R>(L left) implements Either<L, R> { }

    record Right<L, R>(R right) implements Either<L, R> {}
}

ADTs: Json

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 {}
}

ADTs: Errores

interface MovieRepository {
    MovieResponse create(Movie movie);
}

sealed interface MovieResponse permits MovieCreated, MovieResponse {}

record MovieCreated(UUID id) implements MovieResponse {}

ADTs: Errores

sealed interface MovieError extends MovieResponse {
    record DuplicatedMovie(UUID id) implements MovieError {}
    record InvalidDuration(int duration) implements MovieError {}
    record InvalidYear(int year) implements MovieError {}
    record InvalidStars(int stats) implements MovieError {}
    record EmptyTitle() implements MovieError {}
    record EmptyDirector() implements MovieError {}
    record EmptyCast() implements MovieError {}
    record DuplicatedActor(String actor) implements MovieError {}
}

ADTs: Either

interface MovieRepository {
    Either<MovieCreated, MovieError> create(Movie movie);
}

Próximamente :watch:


Unnamed variables and patterns

var result = switch (obj) {
    case Integer _ -> "int";
    case Long _    -> "long";
    case Double _  -> "double";
    case String _  -> "string";
    default        -> "other";
};
  • Incluido en Java 22.
  • Mejora para el pattern matching.
  • Eliminar verbosidad.

Primitive types in patterns

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();
};
  • Preview en Java 23 (sep 2024).

Bola de cristal :crystal_ball:


Derived Record Creation

Point newPoint = oldPoint with {
    x *= 2;
    y *= 2;
};
  • Draft.
  • AKA withers.

Member patterns

var result = switch (optional) {
    case Optional.of(var value) -> value.toString();
    case Optional.empty() -> "empty";
};
  • Early work.
  • AKA deconstructors.
  • Mejora para pattern matching.
  • Cualquier clase.

¿Qué falta todavía?

  • Tail recursion.
  • Soporte de tipos de datos primitivos en genericos.

¿Preguntas?


¡Gracias!


JEPs


Links

-->