I was wondering if there is a simpler or shorter way to write repetitive conditions like x == 1 && y == 1 && z == 1?
CodePudding user response:
If it makes sense you could hold those variables in a class
data class XYZ(
val x: Int,
val y: Int,
val z: Int)
And compare your instance with XYZ(1, 1, 1);
Or if it's just those three variables, you could write
if (Triple(x, y, z) == Triple(1, 1, 1))
CodePudding user response:
val x = 1
val y = 1
var z = 1
println("$x$y$z" == "111") // prints 'true'
z = 2
println("$x$y$z" == "111") // prints 'false'
CodePudding user response:
When it is (exactly) repeated code, you should consider to extract the statement into a method and give a meaningfull name, which you know from the context where it is used. This makes the requirement (reading the code) easier to understand, at the point where it is used. And it makes it also easier to spot the it is always the same condition.
if (conditionName(x, y, z)) {
}
fun boolean conditionName(int x, int y, int z) {
return x == 1 && y == 1 && z == 1;
}
I cannot think of a shorter statement for the condition, but a method extraction will improve your code readability, which should be your overall goal.
CodePudding user response:
listOf(x, y, z).all {it == 1} will return true when x==1, y==1, and z==1.
As well, you could consider using predicates using all.
If the goal is to shorten what you want, there's not much legroom. Some of the other answers have illustrated how to make what you want more readable, however.
