3 ms·
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 optiona
by subtenante 11y ago
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.
public class MatchMap<T, U> {
private final Optional<T> opt;
private final U defaultValue;
private final AtomicReference<U> result = new AtomicReference<U>();
private MatchMap(Optional<T> pOpt, U pDefault) {
super();
opt = pOpt;
defaultValue = pDefault;
}
public MatchMap<T, U> whenMatch(Predicate<T> pPred, Function<T, U> pMapFn) {
if (result.get() != null) {
return this;
}
Optional<T> lFiltered = opt.filter(pPred);
if (lFiltered.isPresent()) {
result.set(pMapFn.apply(lFiltered.get()));
}
return this;
}
public MatchMap<T, U> whenEquals(T pExact, Function<T, U> pMapFn) {
return whenMatch(t -> pExact.equals(t), pMapFn);
}
public U resolve() {
return Optional.ofNullable(result.get())
.orElse(defaultValue);
}
public static <T, U> MatchMap<T, U> of (Optional<T> pOpt, U pDefault) {
return new MatchMap<T, U>(pOpt, pDefault);
}
}
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.
- gizmo385 11y agoI'd love to see how code using your version compares to code using the OP's version. Got any similar examples?
- subtenante 11y agoI 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();
- johnlcox 11y agoI 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.
- nittpicker 11y agoYou can simplify your code a little bit and add some wildcards :) https://gist.github.com/anonymous/7d45e0f746b46684ec45 https://gist.github.com/anonymous/7d45e0f746b46684ec45
- subtenante 11y agoIndeed, thanks!