Can I enforce suboptimal boolean conditions?

Whether the behavior of the boolean or ||

operator in the dart can be changed . For example. I have functions foo()

and boo()

that have a return type bool

. If i write

(foo() || boo()) ? /* A */ : /* B */;

      

and foo()

returns true boo()

will not be executed. I would like to be able to change this, but could not find a way to do it.

I was surprised to see that this doesn't help:

bool helper = false;
helper = helper || foo();
helper = helper || boo();
(helper) ? /* A */ : /* B */

      

+3


source to share


3 answers


boo()

is only executed when it foo()

returns true, because the result will be false anyway (short circuit). You have to force explicit execution like:

var f = foo();
var b = boo();
(f || b) ? print('false') : print('true');

      

If you want to use it inline, you can use a custom method like @AlexandreArdhuin mentioned or



[foo(), boo()].reduce((v1, v2) => v1 || v2)
    ? print('false') : print('true');

      

Try it on DartPad .

+3


source


The literal operators without short circuits is the phrase you are looking for and is not possible at the moment, see https://github.com/dart-lang/sdk/issues/1080



+3


source


You can't use |

in dart
, but you can write a type helper function or

and have the syntax pretty close:

main() {
  if (or([foo(), boo()])) {
    print('ok');
  }
}

bool or(List<bool> values) => values.fold(false, (t, e) => t || e);

bool foo() {
  print("foo");
  return true;
}

bool boo() {
  print("boo");
  return true;
}

      

Try it on DartPad .

+3


source







All Articles