I dont want to put more conditions in ternary operator, rather run 2 statements after evaluating a single condition.
if-else structure would be:
if( maleCardColor == inactiveCardColor ) {
// i want to run both these lines in ternary operator
**maleCardColor = activeCardColor;
femaleCardColor = inactiveCardColor;**
} else {
maleCardColor = inactiveCardColor;
}
i want to use it like:_
maleCardColor = (maleCardColor==inactiveCardColor)? (maleCardColor = activeCardColor && femaleCardColor = inactiveCardColor) : maleCardColor = inactiveCardColor ,
CodePudding user response:
As per my knowledge, if you want to use multi-line in the ternary operator, you can make two methods as mentioned below.
("A" == "B") ? ternaryTrueMethod() : ternaryFalseMethod();
void ternaryTrueMethod() {
/*
multi-line code here
*/
return;
}
void ternaryFalseMethod() {
/*
multi-line code here
*/
return;
}
The first method is for ternary satisfied & the other one is for ternary unsatisfied.
CodePudding user response:
I suppose you could write this, but I would say it has poor readability and a bad style in my opinion.
maleCardColor = (maleCardColor == inactiveCardColor && (femaleCardColor = inactiveCardColor) == inactiveCardColor) ? maleCardColor = activeCardColor : maleCardColor = inactiveCardColor;
The reason this works is because in dart an assignment also returns the value it assigns, so you are doing the assignment as part of the condition for the ternary and simply compare it to the thing you are assigning to. It won't execute if the first part of the condition is already false because it won't even look past the &&
if the condition before it is already false
CodePudding user response:
You can define a run
top-level function and use it to execute multiple statements:
void run(Function() fun) => fun();
It would look like this with the ternary operator:
maleCardColor == inactiveCardColor
? run(() {
maleCardColor = activeCardColor;
femaleCardColor = inactiveCardColor;
})
: maleCardColor = inactiveCardColor;
I believe this is similar to a Kotlin
function with the same name.