0

I quite don't understand how it is valid to write an expression such as:

Comparator<String> stringComp = Comparator.nullsLast(String::compareTo);

Because:

  1. nullsLast accepts a Comparator as argument
  2. the functional method of Comparator is compare(T, T), which accepts two arguments
  3. compareTo accepts only one argument
  4. Without the double-colon operator, I would write: Comparator<String> stringComp = Comparator.nullsLast((s1, s2) -> s1.compareTo(s2));

So does it mean that, when using the double-colon operator on a method accepting only one argument, it is inferred that the method should be called on the first argument of the lambda, using the second argument of the lambda as parameter? It is very surprising to me.

Brian Goetz
  • 90,105
  • 23
  • 150
  • 161
FBB
  • 1,414
  • 2
  • 17
  • 29
  • 1
    See also http://stackoverflow.com/questions/20001427/double-colon-operator-in-java-8?rq=1 – Tunaki Jun 29 '16 at 15:40
  • 4
    This is an _unbound instance method reference_. A one-argument instance method is really a two-argument method, if you count the receiver. Since `compareTo` is an instance method, it needs an extra argument for the receiver, which will be of type `String`. – Brian Goetz Jun 29 '16 at 16:11
  • 3
    Might surprise you only once, then you might notice, how useful this is, considering the number of existing appropriate methods out there, e.g. `Predicate p=String::isEmpty;`. However, there is never a need to refer to the `compareTo` method of a `Comparable`, they all can be handled with, e.g. `Comparator.nullsLast(Comparator.naturalOrder())`… – Holger Jun 29 '16 at 16:28
  • 2
    the 3 types (bound/unbound/static) of method references applicable to your problem: https://gist.github.com/zapl/3bedbf2cce93a14601eb50d1b944481f (type 4 for are constructor references such as `Object::new`) – zapl Jun 29 '16 at 16:56
  • 1
    Thanks for the explanations, and link to the already existing question. I think the accepted answer is not the best, I prefer this one: http://stackoverflow.com/a/23139914/1768736 – FBB Jun 29 '16 at 17:55

0 Answers0