In Java 8 method references are done using the ::
operator.
For Example
// Class that provides the functionality via it's static method
public class AddableUtil {
public static int addThemUp(int i1, int i2){
return i1+i2;
}
}
// Test class
public class AddableTest {
// Lambda expression using static method on a separate class
IAddable addableViaMethodReference = AddableUtil::addThemUp;
...
}
You can see that the addableViaMethodReference
now acts like an alias to AddableUtil::addThemUp
. So addableViaMethodReference()
will perform the same action as AddableUtil.addThemUp()
and return the same value.
Why did they choose to introduce a new operator instead of using an existing one ? I mean, execute a function when the function name ends with ()
and return the function reference when there is no trailing ()
.
Method Execution
AddableUtil.addThemUp();
Method reference
AddableUtil.addThemUp;
Wouldn't this be much simpler and intuitive ? AFAIK, AddableUtil.addThemUp
doesn't currently (Java 7) serve any other purpose and throws a compilation error. Why not use that opportunity instead of creating an entirely new operator ?