5

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;
}
asked Oct 22, 2015 at 11:02

2 Answers 2

9

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;
answered Oct 22, 2015 at 11:12
Sign up to request clarification or add additional context in comments.

Comments

3

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;
answered Oct 22, 2015 at 11:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.