Re:Show HN: Motif – Scala-like pattern matching with Java 8
by subtenante on Wednesday July 22, 2015 @11:24AM
(#9930145)
Funny, I happened to code something just today very similar, but a lot lighter (just two classes, Match for consuming only, and MatchMap for mapping the optional. No when/get, just a when taking two parameters : the predicate and the mapping function.
The class Match is very similar, but takes consumer instead of Function and has some logic to allow several matches to be executed (if several predicates are ok), or only allow the first match to be executed.
[ Parent
| on HN ]
Re:Show HN: Motif – Scala-like pattern matching with Java 8
by nittpicker on Wednesday July 22, 2015 @02:45PM
(#9931499)
You can simplify your code a little bit and add some wildcards :)
Re:Show HN: Motif – Scala-like pattern matching with Java 8
by subtenante on Wednesday July 22, 2015 @04:54PM
(#9932245)
Indeed, thanks!
Re:Show HN: Motif – Scala-like pattern matching with Java 8
by gizmo385 on Wednesday July 22, 2015 @11:40AM
(#9930248)
I'd love to see how code using your version compares to code using the OP's version. Got any similar examples?
Re:Show HN: Motif – Scala-like pattern matching with Java 8
by subtenante on Wednesday July 22, 2015 @12:48PM
(#9930743)
I use it especially for enums so it's like:
MatchMap.of(someOptional, defaultValue)
.whenEquals(MyEnum.VALUEX, v -> someFn(p1, p2))
.whenEquals(MyEnum.VALUEY, v -> otherFn(p1, p2))
.resolve();
Re:Show HN: Motif – Scala-like pattern matching with Java 8
by johnlcox on Wednesday July 22, 2015 @02:33PM
(#9931429)
I haven't tried it with enums, but it should still be possible with Motif. I'll have to add some tests.
match(enumValOpt)
.when(some(eq(MyEnum.VALUEX))).then(() -> someFn(p1, p2))
.when(some(eq(MyEnum.VALUEY))).then(() -> otherFn(p1, p2))
.orElse(defaultValue)
.doMatch();
It's a little longer than your example since there is support for more than just Optional, but it's pretty similar.