Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Question about implicit class argument in Java method reference

In Java, the class portion of a method reference can become the first argument of the function. I’ve seen lots of examples in working code. But I wondered where in the Java Language Specification this is spelled out? I’m wondering because whenever I see code like this, it takes me a few minutes to figure out why there is an "extra" first argument. So I thought it would be helpful to read the actual rule. It does not seem to be mentioned in the sections on functional interfaces or method references.

Here is an example.

import java.util.function.BiFunction;

public class TestBiFunction
{
    public static void main(String[] args) {
        BiFunction<A.B, Integer, Integer> fx = A.B::dbl;
        A.B b = new A.B();
        int result = fx.apply(b, 3);
        System.out.println("Result = " + result);
    }

    private static class A {
        private static class B {
            public int dbl(int x) {
                return 2 * x;
            }
        }
    }
}

So, specifically what I wondered was, in the statement "BiFunction<A.B, Integer> fx = A.B::dbl;", what language rule makes the "A.B" in "A.B::dbl" become the first argument to the BiFunction?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is a pain to find in the Java Language Specification, but I think you’re looking for section 15.13.3, at least in version 8 of the spec, specifically the line

If the compile-time declaration is an instance method, then the target reference is the first formal parameter of the invocation method. Otherwise, there is no target reference.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading