super.t
super.t

Reputation: 2736

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.

Upvotes: 2

Views: 163

Answers (2)

John Kugelman
John Kugelman

Reputation: 361585

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.

Upvotes: 2

khelwood
khelwood

Reputation: 59095

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>.

Upvotes: 1

Related Questions