Hacker News new | past | comments | ask | show | jobs | submit login

You can do this in Java using derive4j: https://github.com/derive4j/derive4j.

It generates code for algebraic data types which offer a typesafe interface similar to the `case` statements in languages that natively support pattern matching.




In the same way you could "do" lambdas with single method interfaces in Java pre-8. It was possible, but it was still a pain to do.


It depends. Bare minimum, in scala you have to do:

  sealed trait Either[A, B]
  final case class Left[A, B](a: A) extends Either[A, B]
  final case class Right[A, B](b: B) extends Either[A, B]
and it is still not a real sum type due to exposing subtyping (cf. https://github.com/quasar-analytics/quasar/wiki/Faking-Sum-T...)

with derive4j:

  @Data
  interface Either<A, B> {
    <X> X match(Function<A, X> left, Function<B, X> right);
  }
or, at your preference:

  @Data
  interface Either<A, B> {
    interface Cases<X> {
      X left(A leftValue);
      X right(B rightValue);
    }
    <X> X match(Cases<X> cases);
  }
So it is actually not much boilerplate.

The real drawback of (any) java implementation is lack of TCO.




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: