简体   繁体   中英

Supplier as a function

How does the following work? I pass a Supplier where a Function is expected.

class Scratch {
    private Bar bar = new Bar("foo");

    public static void main(String[] args) {
        Scratch scratch = new Scratch();
        System.out.println(scratch.getBarValue(Bar::getValue));
    }

    public <T> T getBarValue(Function<Bar, T> extractor) {
        return extractor.apply(bar);
    }

    static class Bar {
        private String value;

        Bar(String value) {
            this.value = value;
        }

        String getValue() {
            return value;
        }
    }
}

I understand Java is creating a function from the supplier, but oddly can't find any documentation around this.

getValue() appears to take no arguments but it actually has an implicit this parameter.

Normally that's disguised behind the syntactical sugar of object.method(...) . When you create a method reference with :: , though, the implicit this becomes explicit. getValue() is then treated as a one-argument function since it can only be called if it knows what Bar it's being called on.

This happens with any instance method. It doesn't apply to static methods; they have no this .

Bar::getValue is a function that accepts a Bar instance and returns a string. It's not a supplier, because without a Bar instance, it cannot be called.

Given a specific instance, bar::getValue is a supplier, because it just gets the value from that particular instance of Bar . But Bar::getValue needs to be given an instance of Bar in order to call getValue() on it. So it's a Function<Bar, String> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM