Let me give some insight into why we added this function to the language when we obviously do not need it (all method references can be expressed as lambdas).
Please note that there is no correct answer. Anyone who says “always use the ref method instead of the lambda” or “always use the lambda instead of the ref method” should be ignored.
This question is very similar in spirit to "when should I use a named class against an anonymous class"? And the answer is the same: when you find it more readable. Of course, there are cases that are unequivocally or unequivocally different, but in the middle there are many grays, and it is necessary to use judgment.
The theory of the refs method is simple: names matter. If the method has a name, then accessing it by name, and not by an imperative package of code that ultimately simply rotates and calls it, is often (but not always!) More understandable and readable.
Arguments about performance or about counting characters are mostly red herrings, and you should ignore them. The goal is to write code that is crystal clear what it does. Very often (but not always!) The refs method wins this metric, so we included them as an option for use in these cases.
A key consideration as to whether the refs method is clarifying or confusing is whether the context is obvious what the form of the function being represented is. In some cases (for example, map(Person::getLastName) , it’s clear from the context that you need a function that maps one thing to another, and in such cases the method references are shiny. In others, using the ref method requires the reader to question which function is described is a warning sign that lambda may be more readable, even if it is longer.
Finally, we found that most people avoid method references at first because they feel even newer and weirder than lambdas, and therefore at first find them “less readable,” but over time, when they get used to the syntax, they usually change their behavior and gravitate towards method references when they can. So keep in mind that your own subjective initial “less readable” reaction will almost certainly entail some aspects of familiarity bias, and you should give yourself a chance to get comfortable with both before expressing a stylistic opinion.
Brian Goetz Jun 30 '14 at 15:39 2014-06-30 15:39
source share