[patterns] Are we considering GADTs for pattern matching?

Andrey Breslav andrey.breslav at jetbrains.com
Tue Aug 1 23:17:01 UTC 2017


Hi,

Since we are looking into pattern matching for Java, I think we should
explore carefully even those features that look more exotic and may never
end up in the final design. Generalized Algebraic Data Types (GADTs)
represent an example of this kind of feature.

Here's a quick and fairly nice description of the feature and some issues
related to it that arose in Scala:
https://gist.github.com/smarter/2e1c564c83bae58c65b4f3f041bfb15f

To recap, we are basically looking at this kind of code:

class Expr<T>
class IntExpr(Integer i) extends Expr<Integer> {}
class BoolExpr(Boolean b) extends Expr<Boolean> {}

<T> T eval(Expr<T> e) {
    switch (e) {
        case IntExpr ie: return ie.i; // Infer T=Integer, so OK to return i
        case BoolExpr be: return be.b; // Infer T=Boolean, so OK to return b
    }
    ...
}

So, the gist of it is that sometimes we can infer the type variables if a
dynamic type test has succeeded. Same would work for if-match .

I see the following questions here:
1. Should we have this in Java at all? It may be a bit more magic than we
are used to having in Java
2. Most issues related to GADTs that I'm aware of arise in the realm of
structural types, i.e. functional languages or declaration-site variance
(which Java luckily doesn't have today), but we'd have to look very
carefully at Java generics to make sure this sort of thing won't blow up
anywhere around wildcards and/or recursive type bounds, for example.

Observation: if we answer "yes" to 1), then this behaviour should be added
as soon as we add any pattern matching, because even the most limited form
of matching includes it. It seems to me that adding this later will be a
breaking change.
-- 
Andrey Breslav
Project Lead of Kotlin
JetBrains
http://kotlinlang.org/
The Drive to Develop
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20170801/a7449db6/attachment.html>


More information about the amber-spec-experts mailing list