The case for no case

Remi Forax forax at univ-mlv.fr
Thu Jun 4 09:17:11 UTC 2020


I was reading the different tests in the pattern branch and an old idea pop up again in my head,
given i was not able to find a mail from me explaining it, here it is.

Currently Java only allow switch on constants, so we write
  String value = ...
  ... switch(value) {
    case "foo" -> ...
  }

The current proposed way to extend the switch syntax to match any type is
  Object value = ...
  ... switch(value) {
    case "foo" -> ...
    case String s -> ...
    default -> ...
  }

This seems to be a kind of natural extension, but it's not the only one.

Because we want to be able to support several kinds of pattern in the future, we have to be careful about the "selector" part, the part before -> or :, of the syntax, otherwise we may not be able to express all the patterns we want.
One simple solution is to use different keyword for different kind of patterns,
by example, "case" for a constant pattern, "instanceof" for the type pattern, "default" the default pattern, etc

using this new syntax, the same code as above will be written that way
  Object value = ...
  ... switch(value) {
    case "foo" -> ...
    instanceof String s -> ...
    default -> ...
  }

This idea allows by example to add the "when" pattern that execute an arbitrary boolean expression,
  var list = ...
  ... switch(value) {
    when list.contains(value) -> ...
  }

and to combines patterns
  var list = ...
  ... switch(value) {
    instanceof String s and when !s.isEmpty() -> ....
  }

regards,
Rémi


More information about the amber-spec-experts mailing list