In this blog, we will talk about Java 8 double colon :: operator as an alternative to Lamda expression.

Functional Interface implementation method can be mapped by using :: (double colon) operator

Take a look at the simple lamda expression

MyFunctionalInterface lamdaExpr = () -> System.out.println("methodOne lamda expression implementation");
lamdaExpr.methodOne();


In the above case MyFunctionalInterface is functional interface and having a method methodOne, which is referenced as lamdaExpr lamda expression.

The main benefit we get from double colon operator is of code re-usability and readability.

Alternatively, we can achieve the same by another way. Suppose we already have a method(static or non static) and which has required implementation, double colon operator allows us reuse the existing method. Take Look at the below code

MyFunctionalInterface iDoubleColon = MethodReference::methodTwo;
iDoubleColon.methodOne();


Here MethodReference is class having method methodTwo with same argument type, now can be reused in this case.

Method Reference

Any method(static or non static) can be mapped to SAM as long as the arguments types are same. There are no restriction on method name, return type, modifier, class hierarchy which can be anything.

Static method reference

Syntax:
Classname::methodName

Non Static method reference

Syntax:
objref::methodName

Constructor Reference

We can use :: ( double colon )operator to refer constructors also
Syntax:
classname :: new

Consider a constructor implementation below

public ConstructorReference() {
   System.out.println("ConstructorReference constructor implementation");
}

The same constructor can be reused using double colon operator as below

MyFunctionalInterface2 consRef = ConstructorReference::new;
consRef.get();


Here get is the abstract method in our Functional Interface MyFunctionalInterface2.
Watch out for the new keyword after ::.

The same can be achieved using lamda expression as below

MyFunctionalInterface2 lamdaExpr = () -> {
    ConstructorReference obj = new ConstructorReference();
    return obj;
};
lamdaExpr.get();


Conclusion

As we saw we can use double colon operator where ever lamda expression is expected. The main benefit we get of code re-usability and readability. The complete source code for the example is available in this GitHub project.

© Copyright Instance Of Cake 2023