Earlier quoted context omitted.
Ok, it's perhaps a true Scotsman argument but saying that Java as a syntax for ADT is like saying JS (pre 2015) has classes because it can be simulated by function + prototype or that Java (pre 8) has lambdas because it can be simulated by anonymous classes. Java misses the syntactic sugar to define ADT in one place like in Standard ML, OCaml or F#. The closest you get is to declare records inside a sealed interface,…
> Java misses the syntactic sugar to define ADT in one place like in Standard ML, OCaml or F#. I don't think so. > I was not able to define a classical list with cons and nil in Java. If you want to restrict Nil to a single instance, don't make it a record class: sealed interface List { static List cons(T car, List cdr) { return new Cons (car, cdr); } static List nil() { return (List )Nil.INSTANCE; } record Cons (T c…
List list = cons("a", nil());
switch(list) {
case Cons(var car, var cdr) -> ...
case Nil -> ...
}
Nil is typed List which is not compatible with List.You may be able to use extractors as the inverse of the static methods cons() and nil() but that adds more boilerplate.
Disjunctive enums like in Rust or Scala 3 is a simpler way to define ADT.