Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a setter (not the value) as parameter to a function without reflection?

Tags:

dart

I want to pass the setter of a class' field as parameter to a function so the function can do the assignment.

Is there a way without using reflection?

like image 415
Günter Zöchbauer Avatar asked Mar 05 '14 07:03

Günter Zöchbauer


People also ask

Do setters need parameters?

The setter method takes a parameter and assigns it to the attribute. Getters and setters allow control over the values.

How many parameters does a setter have?

Setters only take one parameter because they are special methods that expect a value and set the property to that value, upon validation of type.


1 Answers

You can't directly pass the setter.

To avoid reflection you can wrap the setter inside a function :

class A {
  String _attr=;
  set attr(String v) => _attr = v;
}

main() {
  final a = new A();

  // create a wrapper function to set attr
  final setter = (v) => a.attr = v;

  callSetter(setter);
  print(a._attr);
}

callSetter(setterFunction(value)) {
  setterFunction("value");
}

This proposal about generalized tear offs is approved and will probably implemented soon and allows to closurize getters and setters like:

var setter = a#attr;
// and can be invoked like
setter(value)
like image 78
Alexandre Ardhuin Avatar answered Sep 21 '22 04:09

Alexandre Ardhuin