New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Enhance javaslang.match.Match by caze(Pattern p, Function<Object, Boolean> o) #8
Comments
Pattern Matching with Java 8MotivationIn Scala it is possible to decompose and match complex objects: val option = Option("hi")
option match {
case Some(a : String) => "str value: " + a
case None => "no value"
} How cool would it be, if something similar were possible with Java! Approach
Decomposition could take place in two flavors: 1) Using Tuples@FunctionalInterface
interface Decomposition<T, R extends Tuple> {
R unapply(T obj);
} Example: class A {
String val1;
int val2;
}
final Decomposition<A, Tuple2> deA = a -> Tuple.of(a.val1, a.val2);
Matchs.caze(deA, Tuple.of("1", any()), t -> t._2);
Matchs.caze(deA, Tuple.of("1", any()), (Tuple2 t) -> t._2); Further, the decomposition of objects could be simplified by native support: interface Decomposable<T, R extends Tuple> {
Decomposition<T, R> decomposition();
} Example: class A implements Decomposable<A, Tuple2> {
String val1;
int val2;
@Override
Decomposition<A, Tuple2> decomposition() {
return a -> Tuple.of(a.val1, a.val2);
}
}
_// would decompose any object_
Matches.caze(Tuple.of("1", any()), t -> t._2);
Matches.caze(Tuple.of("1", any()), (Tuple2 t) -> t._2);
_// would decompose objects of type A_
Matches.caze(A.class, Tuple.of("1", any()), t -> t._2);
Matches.caze(A.class, Tuple.of("1", any()), (Tuple2 t) -> t._2); Pro: simple value object impl Using View interfaceTODO Pro: explicite types & names |
Prototypically implemented. Depends of https://bugs.eclipse.org/bugs/show_bug.cgi?id=442245. Need to implement public static <T, P1, P2, ..., Pn, R1, R2, ..., Rn> Pattern<T, Tuple2<P1, P2, ..., Pn>, Tuple2<R1, R2, ..., Rn>>
of(Decomposition<T, Tuple2<R1, R2, ..., Rn>> decomposition, Tuple2<P1, P2, ..., Pn> prototype) for 3 <= n <= 13. |
Invent a Pattern interface which adds more mature pattern matching capabilities to Match API.
Focus lies on object decomposition using type and value information. Wildcards would be great.
Brainstorming:
Additionally, it would be nice to provide a programatic way to create Patterns instead of an interface declaration, e.g. via Annotation, Builder, ...
The constraint is, as always for Javaslang, to use only JVM (+ Javaslang) classes and no 3rd party libs.
The text was updated successfully, but these errors were encountered: