Friday, November 9, 2018

Java 8 - Method References

Greetings!

In Java we have object references. We pass objects around. What if we can pass reference to a method?
In Java 8 if we are executing only one method we can do this using lambda expressions.

For an example these are equal.   
     

(x) -> System.out.print(x)
System.out::print


As you can see, :: separates the name of the method from the class/ object. There are 3 ways we can use method references.
  1. object::method - object.method(parameters)
  2. Class::staticMethod - Class.staticMethod(parameters)
  3. Class::instanceMethod - firstParameter.method(parameters)
In first 2 cases, parameters become the methods parameters. As you can see in System.out::print. If we have more than 1 parameters it is still same,

(x, y) -> Math.pow(x, y)
Math::pow


Third case is different. First parameter becomes the target object of the method and rest become the parameters. For example,

// (object, arguments) -> object.method(arguments)
name -> name.toUpperCase()
String::toUpperCase


We can use this and super also the same way;

this::instanceMethod
super::instanceMethod


inner class => lambda expression => method reference

No comments:

Post a Comment