Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart can you overload the assignment operator?

I have the following class:

class EventableNumber{

  num _val;

  num get val => _val;

  void set val(num v){

    num oldValue = _val;
    _val = v;
    _controller.add(new NumberChangedEvent(oldValue, v));

  }

  StreamController<NumberChangedEvent> _controller = new StreamController<NumberChangedEvent>();
  Stream<NumberChangedEvent> _stream;
  Stream<NumberChangedEvent> get onChange => (_stream != null) ? _stream : _stream = _controller.stream.asBroadcastStream();

  EventableNumber([num this._val = 0]);

}

Is it possible to overload the = assignment operator? rather than using the val getter and setter to enforce the event to fire when the value changes it would be nice if it could just be done when the user writes myEventableNum = 34 and then myEventableNum first its onChange event, rather than myEventableNum.val = 34.

like image 583
Daniel Robinson Avatar asked Nov 12 '13 21:11

Daniel Robinson


1 Answers

Dart doesn't allow this.

However, have you considered a function style call?

Basically, if you define a function called 'call' in EventableNumber class, then you can call the instance as a function:

myEventableNum(34)

If you decided to go this way, it is recommended to implement the Function interface:

class EventableNumber implements Function {
...
  void call(val) {...}
...
}

Hope this helps :)

like image 58
Sam Avatar answered Oct 01 '22 05:10

Sam