Are there delegates in Java 8?
If not, how do we have lambda expressions in JDK 8 without delegates?
What are method references? Are they the same as delegates?
Are there delegates in Java 8?
If not, how do we have lambda expressions in JDK 8 without delegates?
What are method references? Are they the same as delegates?
Thanks to Pacerier's comment on the question, here is a way to accomplish what a C# (one-function) delegate does, even in Java 7 or below.
usage
yields
NOTE: If you only need a single implementation per-class of a given 'delegate', then the simpler solution is to directly implement the interface on the class. Here is an example. The class already had
f3
, and now it is extended to implementIA
:In this case, it is no different than any other interface implementation. The point is that the
design concept
return a function that matches a specified signature can be satisfied, with a bit of extra coding, using Java interfaces. In the second, simpler, case, the interface is placed directly on the class. In the first, more general, case, the interface is placed on an anonymous instance of an anonymous inner class. For clarity and easy access, I isolate those 'delegate creators' in wrapper functions.It is true that the result isn't quite the same as a C# delegate, because one has to do
ia.f()
rather thania()
. Nevertheless, the design goal has been met.NOTE: In Java 8, the coding is simplified by use of lambdas. I'm not using Java 8, so I won't include the Java 8 implementation here. (Anyone is welcome to submit an edit that adds that implementation. I suggest showing new bodies below for my
wrapF1()
andwrapF2()
above, as that would make it easy to compare Java 7 and Java 8 versions.)There are no delegates in JDK 8. Under the hood lambdas are instances of functional interfaces (an interface with exactly one abstract method). Depending on where you are passing your lambda the compiler can figure out what interface it is implementing. For example the Collections.sort method accepts a Comparator instance as a second parameter. The Comparator happens to be a functional interface so the compiler will check if the lambda you are passing matches the abstract method in Comparator or not.
A Method reference is just a simplification. When your lambda is just calling an existing method you can use this new syntax to simplify the construct. The example from the linked tutorial shows it pretty well:
instead of:
it's simpler with method reference:
Have a look on the lambdafaq.