Method references
Method references give idiomatic feel to the function reference there by making the code more readable.
If the lambda expression is only having a call to other instance method, then, the lambda syntax can be replaced by that method reference.
It is just a syntactic change, nothing more than that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | private void test(Consumer<? super Integer> consumer){ //..... } public void instantiateConsumer(){ //Before Lambda's - Prior to Java 8 test(new Consumer<Integer>() { @Override public void accept(Integer val) { System.out.println(val); } }); //Using Lambda test(val -> System.out.println(val)); //Method reference test(System.out::println); } |
Using the method reference, above code is simplified verbosely using Lambda first and method reference later.
Prior to Java 8, we had to create a class for consuming a method since method was not a first class citizen in java which means method was not treated the same way as object. methods cant be passed as arguments. you need to wrap them inside a class.
Comments
Post a Comment