TIL-30: Method References in 3 Minutes — Prefer Method References to Lambdas
“Today I learned that between using method references or lambda expression, the one that makes the code simpler should be the choice.”
In the previous post, we talked about Lambda Expressions and that we need to use them whenever we use Functional Interfaces. In this post, we are going to look at using Method References instead of Lambda expressions, whenever it makes it our code simpler.
Method References
This is another great feature introduced in Java 8. Method references are a way to generate function objects (instances of Functional Interfaces) just like Lambda Expressions. However, if lambda expressions take many parameters, they start to get complex and reduce code readability.
To cure that, method references make great substitutes whenever you are making a single method call in your lambda expression.
str -> str.parseInt(str) // LambdaString::parseInt // Method Reference
Internals
First I saw the code above, I asked, “How does that even work?”. To getter grasp of it, we may need to look at 3 different usages of Method References.
1- Method Reference to a Static Method.
2- Method Reference to an Instance Method.
3- Method Reference to a Constructor.
1- Method Reference to a Static Method
We directly call the reference to the static method of the “AgeComparison” class. The types for arguments for that method are inferred by the JRE. For more detail on this topic please, see.
ClassName::staticMethodName
2- Method Reference to an Instance Method
Here we call the reference to a method of an instance.
instanceName::instanceMethodName
3- Method Reference to a Constructor
Constructor references serve as factory objects.
The usage of constructor references is similar to the static method references. Only we call new as the method name.
ClassName::new
The constructor references of Person class is assigned to an instance of PersonFactory, it is possible since the function descriptor of Person constructor matches the abstract getPerson method in PersonFactory. They both accept an int value and return a Person.
(int) -> Person
The catchy thing here is that the constructor of Person class is not yet called. When we call the getPerson(int) of the functional interface, it is when the constructor of Person class is called!
Conclusion
Method references should be used whenever a lambda expression with a single method call gets complex due to the number of its parameters. It makes your code clearer and more readable.
Cheers!