1

Say I have

class Cls {
  int val;
  int method();
}

var obj = Cls();

void f(int Function() arg) {...}

Of course, I can use

f(obj.method);

However, I cannot use

f(obj.val_as_a_getter_method)

but have to write the verbose

f(()=>obj.val)

I hope I can have something like in Java, where using lombok we get those setter and getter methods, so we can call

f(obj.getVal)

Of course, similar things happens for setters. For brievity I do not repeat here.

Currently I write my own code generator that automatically generates setters and getters. Is there any better ways?

Thanks!

ch271828n
  • 15,854
  • 5
  • 53
  • 88
  • Why do you need a `set` and `get` method? Dart supports properties where you can later add a getter/setter for a given variable if you need to run some code when accessing the variable. This is not possible in Java which is why it is recommended to use get/set methods in Java. See the section "Getters and setters" here: https://dart.dev/guides/language/language-tour#methods – julemand101 May 14 '21 at 13:18
  • @julemand101 Because I have that `f` function which accpets a *function of type `int Function()`* as argument. – ch271828n May 14 '21 at 13:22
  • @julemand101 question edited – ch271828n May 14 '21 at 13:23
  • Ah ok, now I understand. No, Dart does not have this feature so you will need to write `()=>obj.val`. – julemand101 May 14 '21 at 13:25
  • @julemand101 ah sounds not that beautiful :( – ch271828n May 14 '21 at 13:33
  • Well, the reason is that get/set properties should be transparent for the user and should therefore be seen as normal variables. Since Dart does always pass by value, you will just get a copy of the value and not a reference to the value inside the class: https://stackoverflow.com/questions/18258267/is-there-a-way-to-pass-a-primitive-parameter-by-reference-in-dart/18273525 – julemand101 May 14 '21 at 13:35
  • https://github.com/dart-lang/language/issues/691 – jamesdlin May 14 '21 at 20:49

0 Answers0