3 ms·
> If you have an interface with a single method, or something with a single varying piece of behavior, please strongly consider accepting a function instead. J
by azth 4y ago
> If you have an interface with a single method, or something with a single varying piece of behavior, please strongly consider accepting a function instead.
Java neatly solves this by means of Functional Interfaces. Interfaces that have a single method related to the generic type parameter can be called by using lambda syntax. Take for example sorting:
<T> void sort(T[] a, Comparator<? super T> c)
A `Comparator<T>` has a method `int compare(T o1, T o2)`, which allows the caller to invoke `Arrays.sort` by passing a lambda:
Arrays.sort(list, (l1, l2) -> l1.compareTo(l2));
- Groxx 4y agoI don't think I'd call this "neatly"... more "a weird but pragmatic hack to improve an incredibly common pattern that had no concise option prior to java 8". And it kinda encourages continuing the "keep declaring a lambda that could have just been a function reference if the API had used a function instead" pattern, which is not great. But I do very much like it. It improves Java's ergonomics quite a lot.
- layer8 4y agoWhat I like about Java functional interfaces is that they give a place to specify an interface contract. For example, with Comparator, it specifies that instances must implement a total ordering. Purely structural function types don't have that affordance. A slightly problematic point, however, is that you can assign a method reference from one functional interface to a variable of another functional interface based purely on structural typing, even if they happen to have incompatible interface contracts. For example, if you had a PartialOrder functional interface with the same parameter/return types as Comparator, then you could assign PartialOrder::compare to a Comparator variable although the semantics aren't compatible. Whereas nominal typing prevents you from assigning a PartialOrder to Comparator (no "duck typing"), Java circumvents the nominal type system here for method references, with the result that one may assign incompatible implementations without noticing.
- watwut 4y ago> keep declaring a lambda that could have just been a function reference Yes, but those are less readable, too much syntax and not enough javadoc/names on them.