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;
}
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With