sábado, 20 de marzo de 2021

Records en java 16

 


Ya hable de java 16, ahora vamos a ver una de sus mejoras: Records

El objetivo de los records es poder diseñar de forma rápida, tipos de datos compuestos inmutables. Esta característica no viene a remplazar nuestras queridas clases.  

Antes de java 16 debíamos hacer una clase para representar un tipo de dato inmutable, por ejemplo Point : 

class Point {

    private final int x;

    private final int y;

    Point(int x, int y) {

        this.x = x;

        this.y = y;

    }

    int x() { return x; }

    int y() { return y; }

    public boolean equals(Object o) {

        if (!(o instanceof Point)) return false;

        Point other = (Point) o;

        return other.x == x && other.y == y;

    }

    public int hashCode() {

        return Objects.hash(x, y);

    }

    public String toString() {

        return String.format("Point[x=%d, y=%d]", x, y);

    }

}

Ahora podemos utilizar records : 

record Point(int x, int y) { }

Por lo visto, mucho menos código; record nos ofrece metodos y constructores por defecto y por supuesto que podemos sobreescribirlos, un ejemplo sería : 

record SmallPoint(int x, int y) {

  public int x() { return this.x < 100 ? this.x : 100; }

  public int y() { return this.y < 100 ? this.y : 100; }

}

Sin más dejo link: https://openjdk.java.net/jeps/395



No hay comentarios.:

Publicar un comentario