Getting to know Kotlin!
var flag = false;
if(condition) {
//do one thing
flag = true;
}
if(condition2) {
//do another thing
flag = true;
}
if(flag)
save();
What is the right way to do this in Kotlin avoiding the flag
approach?
CodePudding user response:
I don't see any clever way to do it concisely in Kotlin, but in most cases I would probably prefer assigning conditions to variables over the flag
approach:
val isBlue = ... some condition ...
val hasWings = ... another condition ...
if (isBlue) {
...
}
if (hasWings) {
...
}
if (isBlue || hasWings) {
...
}
Of course, it is a matter of personal taste.
Also, in some cases flag
makes more sense. There is save()
in your example, so if this flag is something like shouldSaveData
and it depends on several conditions where for example the data is mutated, then flag
approach makes perfect sense.