Method References Cannot Always Replace Lambda Expressions
A couple of weeks ago, I gave one of my “Writing awesome Java code” workshops. While I was explaining ways of designing APIs using lambda expressions, a participant asked a question that I couldn’t answer. There was a simple lambda expression in the example code, and the question was if it could be replaced with a method reference. I agreed and changed it to a method reference. However, the code didn’t compile. That confused me, of course. After having thought for a while, the answer came to me — and it’s pretty simple. In this article, I want to share my insights.
There are two simple methods, one without any parameters, one with exactly one parameter:
The following test documents that the lambda expression in line 15 cannot be replaced with the method reference in line 16. The reason for this is that the lambda expression is of the same signature than the required function, which needs one Integer parameter “in” and one Integer as a return value. However, the lambda ignores the “in” parameter because methodWithoutParameter() is called without using k at all. That works fine for the lambda. However, the method reference needs the exact signature and doesn’t work otherwise.
So, what can be expressed with a lamba cannot be necessarily expressed with a method reference.
via DZone.com Feed https://dzone.com
May 16, 2017 at 11:30AM