7 ms·
I'm not sure if I catch your drift, but if I do: public <T, Z, F extends Function<? super T, Z>> Z apply(Function<F, Z> target, F fn) { return targ
by p2t2p 6y ago
I'm not sure if I catch your drift, but if I do:
public <T, Z, F extends Function<? super T, Z>> Z apply(Function<F, Z> target, F fn) {
return target.apply(fn);
}
@Test
public void test() throws Exception {
Stream<String> stream = Stream.of("foo", "bar", "baz");
stream = apply(stream::flatMap, s -> Stream.of(s + "_a", s + "_b"));
System.out.println(stream.collect(toList()));
Optional<String> bean = Optional.of("bean");
bean = apply(bean::flatMap, b -> Optional.of("soy"));
System.out.println(bean);
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "hello");
CompletableFuture<String> future2 = apply(future1::thenCompose, string -> CompletableFuture.supplyAsync(() -> string + " world"));
System.out.println(future2.get());
}
Output:
[foo_a, foo_b, bar_a, bar_b, baz_a, baz_b]
Optional[soy]
hello world
- mrkeen 6y agoThis is interesting stuff. I'm trying to figure out how to refer to flatMap directly from the abstract function, e.g. flatMapTwice(x, fun) { return x.flatMap(fun).flatMap(fun); } or chain(x, fun1, fun2) { return x.flatMap(fun1).flatMap(fun2); } It should also preserve the type information (just like you did above). I don't want the caller to need to downcast from FlatMappable. It doesn't need to be x.flatMap(f) - I'd be interested seeing a flatMap(x, f) version.