Philipp
Philipp

Reputation: 539

Dart: Is there a way to negate and return a boolean in a single line?

Is there a way to write the follwoing funciton as a single line, using the fat arrow (=>) notation?

 bool tick() {
   _tick = !_tick;
   return _tick;
 }

Upvotes: 3

Views: 4906

Answers (2)

Stewie Griffin
Stewie Griffin

Reputation: 5608

The following thick() method will negate _tick and return the newly assigned value:

bool tick() => _tick = !_tick;

Upvotes: 4

Peter Koltai
Peter Koltai

Reputation: 9734

Simply:

bool tick() => !_tick;

_tick should be defined, and this function will return negated value. So you have to assign the result in order to negate. Like this:

void main() {
  bool _tick = true;
  _tick = tick(_tick);
  print(_tick); 
  _tick = tick(_tick);
  print(_tick); 
}

bool tick(tick) => !tick;

The above will print:

false
true

If you'd like to have a variable declared and have this negated in a function you can try:

class Tick {
  bool tick;
  Tick(this.tick);
}

void tick(Tick data) => data.tick = !data.tick;

main() {
  var data = new Tick(true);
  print(data.tick); // true
  tick(data);
  print(data.tick); // false
  tick(data);
  print(data.tick); // true
}

Upvotes: 2

Related Questions