3 ms·
> and function signatures like the below might be "clunky" from your point of view, but IMHO are more clear since they document explicit types. (and you can nav
by gavinray 3y ago
> and function signatures like the below might be "clunky" from your point of view, but IMHO are more clear since they document explicit types. (and you can navigate to their javadoc)
Blah doSomething(BiFunction<String, Integer, Foo> fn)
What happens when you want to pass a function of arity 3, 4, 5 or 6?
Also, it's nice to be able to give identifiers to the arguments:
// In Kotlin (absurd example, just to prove a point)
fun withHandler(
handler: (name: String, age: Int, isAdult: Boolean, callback: (Int, Int, Int) -> Unit) -> Unit
) {
handler("John", 25, true) { println(it, it, it) }
}
// In Java:
interface Handler {
void handle(String name, int age, boolean isAdult, Callback callback);
}
interface Callback {
void call(int a, int b, int c);
}
class JavaClass {
public static void withHandler(Handler handler) {
handler.handle("John", 25, true, (a, b, c) -> {
System.out.println("a: " + a + ", b: " + b + ", c: " + c);
});
}
}
- lenkite 3y agoIt is possible to create custom functional interfaces in Java. One is not restricted to what is provided in the stdlib. @FunctionalInterface public interface VargsFunction<T,R> { R apply(T... t); } @FunctionalInterface public interface QuadFunction<T, U, V, W, R> { public R apply(T t, U u, V v, W w); } Of-course Java is nowhere as flexible as C++ in this regard which has variadic templates, template parameter packs and template-template parameters. Well, you can do this with currying if one is feeling lazy, but obviously not recommended: Function<One, Function<Two, Function<Three, Function<Four, Function<Five, Six>>>>> func = a -> b -> c -> d -> e -> 'z'; The second point (named parameters) is one that several language designer greybeards (not just Java) have taken a deliberate design decision against for varying reasons. Use builders/records/structs is the usual advice given here anytime you ask them this question.