Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Function Reference With Arguments

Trying to understand how to reference Instance functions. I've figured out how to define getters, but setters are giving me trouble. I'm not sure how to write a function for a given method signature and a given base class.

What type is Foo::setBar below?

public class Foo {
    private String bar;

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }
}


{
    //Works great!
    Function<Foo, String> func1 = Foo::getBar;

    //Compile error ?
    Function<Foo, String> func2 = Foo::setBar;
    //Compile error ?
    Function<Foo, Void, String> func3 = Foo::setBar;
}
like image 973
Jason Avatar asked Oct 22 '15 11:10

Jason


2 Answers

Your Function<Foo, String> func2 = Foo::setBar; is a compile error, because public void setBar(String bar) ist not a function from Foo to String, it is actually a function from String to Void.

If you want to pass the setter as method reference, you need a BiConsumer, taking a Foo and a String like

final BiConsumer<Foo, String> setter = Foo::setBar;

Or if you already got an instance of foo, you can simply use this and use a Consumer, e.g.

Foo foo = new Foo();
final Consumer<String> setBar = foo::setBar;
like image 150
Martin Seeler Avatar answered Sep 26 '22 07:09

Martin Seeler


As setBar has a void return type, the matching functional interface single abstract method must have void return type as well. Such functional interfaces are commonly referred as "consumers". In your particular case you need to use BiConsumer which accepts a Foo object and a new bar value:

BiConsumer<Foo, String> func2 = Foo::setBar;
like image 33
Tagir Valeev Avatar answered Sep 25 '22 07:09

Tagir Valeev