Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda matches signature of a FunctionalInterface, yet "does not". How do you explain that the argument is passed at all?

I am working on this project currently. It works surprisingly well.

Yet, after re-reading the README again, I started to wonder about how to document something that is bugging me...

To quote the example, and forgetting for a moment that exceptions can be thrown, it reads:

Files.list(somePath).map(Path::toRealPath).forEach(System.out::println)

OK. Now, the method of Path involved is this one. Of course, we do not pass any LinkOption.

Again: let's forget for a moment that it throws any exception.

Stream's .map() takes a Function as an argument. This interface, for Function<T, R>, is defined as:

R apply(T t);

But the method I am using accepts no arguments. At a first glance, it does not seem to match a Function, right? Except that...

It can be written as:

path -> path.toRealPath()

It therefore looks like the mechanism used is somewhat able to invoke a method on the "stream object" if the method reference has no argument, or something like that...

I'd like to document this accordingly, and I am missing something here.

What am I missing?

like image 878
fge Avatar asked Oct 20 '22 20:10

fge


1 Answers

Non-static methods have the receiver (this) object as an implicit first argument. Therefore, Class::nonStaticMethod has one more argument than you might expect.

Java Language Specification Section 15.13.1, Compile-Time Declaration of a Method Reference:

  • Second, given a targeted function type with n parameters, a set of potentially applicable methods is identified:

    • If the method reference expression has the form ReferenceType :: [TypeArguments] Identifier, the potentially applicable methods are the member methods of the type to search that have an appropriate name (given by Identifier), accessibility, arity (n or n-1), and type argument arity (derived from [TypeArguments]), as specified in §15.12.2.1.

      Two different arities, n and n-1, are considered, to account for the possibility that this form refers to either a static method or an instance method.

like image 157
Chris Jester-Young Avatar answered Nov 02 '22 08:11

Chris Jester-Young