2

I have found an example with java predicate functional interface:

BiPredicate<String, String> b1 = String::startsWith;
BiPredicate<String, String> b2 =
            (string, prefix) -> string.startsWith(prefix);
System.out.println(b1.test("chicken", "chick"));
System.out.println(b2.test("chicken", "chick"));

I understand how b2 works - it's clear. How does the compiler understand how to use the b1 method? Method boolean startWith(String str) has only one parameter. String class doesn't have
boolean startWith(String srt1, String srt2) method.

user3756506
  • 431
  • 1
  • 3
  • 12

1 Answers1

5

Method startWith(String str) has only one parameter.

Actually String.startsWith has an implicit this parameter because you’re calling it on an object instance. Thus it conforms to a functional interface with two String parameters.

As mentioned by Giorgi, you should consult the documentation on method references, since there’s a lot more to this syntax, and the way it works when the name before :: refers to an object versus a class name.

Briefly, there are four cases. Assuming a functional interface for a method call with two parameters a and b:

  1. Class::staticMethod

    This is equivalent to (a, b) -> Class.staticMethod(a, b).

  2. object::method

    This is equivalent to (a, b) -> object.method(a, b).

  3. Class::method

    This is equivalent to (a, b) -> a.method(b).

  4. Class::new

    This is equivalent to (a, b) -> new Class(a, b).

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214