This post talks about one of the coolest feature of Java 8; method references!
Methods are no longer second class values in Java 8. Just like object references which can be passed around as values, methods can also be passed around as values. To achieve this, Java 8 provides notation, :: (along with lambda, off course)
You might argue that, lambda functions do the same thing. And you are write to a great extent. The only fundamental difference is that, this way you can simply refer to a method without writing the full body of the method (as we do in lambda).
Lambda vs Method Reference
Function<Double, Double> square = (Double d) -> d * d; //lambda
Function<Double, Double> square = Arithmatic::square //method reference
Arithmatic::square is a method reference to the method getSquare defined in the Arithmatic class. Brackets are not needed because we aren't calling the method actually.
(String s) -> System.out.println(s) //lambda
System.out::println //method reference
In lambda, you just call the method without it's name but in method reference you explicitly refer it by name. This way, code is more readable.
--
happy functional programming !
Methods are no longer second class values in Java 8. Just like object references which can be passed around as values, methods can also be passed around as values. To achieve this, Java 8 provides notation, :: (along with lambda, off course)
You might argue that, lambda functions do the same thing. And you are write to a great extent. The only fundamental difference is that, this way you can simply refer to a method without writing the full body of the method (as we do in lambda).
Lambda vs Method Reference
Function<Double, Double> square = (Double d) -> d * d; //lambda
Function<Double, Double> square = Arithmatic::square //method reference
Arithmatic::square is a method reference to the method getSquare defined in the Arithmatic class. Brackets are not needed because we aren't calling the method actually.
(String s) -> System.out.println(s) //lambda
System.out::println //method reference
In lambda, you just call the method without it's name but in method reference you explicitly refer it by name. This way, code is more readable.
--
happy functional programming !