5

I have multiple variables which needs the same check in a if-statement in Dart. I need to know if there is at least one of the variables > 0.

For example:

var a = 1;
var b = 0;
var c = 0;

if ((a > 0) || (b > 0) || (c > 0)) {
  print('Yeh!');
}

This should be done easier, like in Python.

The following code isn't valid, but I tried this:

if ((a || b || c) > 0) {
  print('Yeh!');
}

Any tips would be nice.

julemand101
  • 28,470
  • 5
  • 52
  • 48
Johan Walhout
  • 1,446
  • 3
  • 22
  • 38
  • 1
    Even in Python, `(a or b or c) > 0` works only in *that particular case*. It wouldn't work if your comparison were, say, `> 1`, or if `a` were `-1`. IMO `(a or b or c) > 0` would be dangerously misleading. – jamesdlin Sep 10 '20 at 10:54

1 Answers1

3

One way would be to create a List and to use Iterable.any:

if ([a, b, c].any((x) => x > 0)) {
  print('Yeh!');
}
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • Has this answer disadvantages over doing it like OP did first e. g. is it way slower? – kk_ Jul 18 '22 at 17:26
  • 1
    @kk_ I'd expect it to be slightly slower since it would need it would need to 1. Construct a `List`, 2. Invoke a method call, 3. Iterate over the `List`, 4. Invoke a function for each element. That said, I wouldn't expect that performance difference to be a concern since we're talking about a fixed (and likely not very large) number of items. – jamesdlin Jul 18 '22 at 18:27