JEP 427 and objects meant to replace null

Remi Forax forax at univ-mlv.fr
Wed Apr 27 14:32:33 UTC 2022


----- Original Message -----
> From: "P Holder" <pholder at gmail.com>
> To: "amber-dev" <amber-dev at openjdk.java.net>
> Sent: Wednesday, April 27, 2022 1:55:08 AM
> Subject: JEP 427 and objects meant to replace null

> I was just looking at the null handling parts of
> JEP 427: Pattern Matching for switch (Third Preview)
> and wondering how it would impact the way I code.
> 
> I personally go to great efforts to avoid null.  If I need an "out of
> band" signal for an object, I make a public static final  special
> value to use in the place of null, especially in initializers.
> 
> I was wondering if there is any logical way to handle these special
> cases? (sorry for the pun)
> 
> so if I have
> 
> class Shape
> {
>  public static final Shape UNDEFINED_SHAPE = new Shape();
> ...
> }
> 
> could I have
> 
> static void testTriangle(Shape s) {
>    switch (s) {
>        case null, UNDEFINED_SHAPE ->
>            System.out.println("An undefined shape");
>       case Triangle t
>        when t.calculateArea() > 100 ->
>            System.out.println("Large triangle");
>        default ->
>            System.out.println("A shape, possibly a small triangle");
>    }
> }

The current workaround is to use "when"

  switch(s) {
     case Triangle t -> ...
     case Shape s when s == UNDEFINED_SHAPE ->
     default -> ...
  }

The main reason to not introduce a constant pattern as you are suggesting is that when mixed with the record pattern people will think that it's a method call while it's not.
By example,
  switch(o) {
    case Point(2, 3) -> 
  }

is not equivalent to
  o.equals(new Point(2, 3))

but is equivalent to
  if (o instanceof Point p && p.x() == 2 && p.y() == 3)

At some point in the future, we may want to have a constant pattern, but maybe with another syntax, C# uses "== constant" by example.
Or we may decide that having a when condition is enough.
  case Point(var x, var y) when x == 2 && y == 3

Rémi


More information about the amber-dev mailing list