skip to Main Content

I was wondering if there is a simpler or shorter way to write repetitive conditions like x == 1 && y == 1 && z == 1?

5

Answers


  1. You could consider using predicates using all. For example:

    listOf(x, y, z).all {it == 1}
    

    This will return true when x==1, y==1, and z==1.

    If the goal is to shorten what you want, there’s not much legroom as your boolean expression is already very concise. Some of the other answers have illustrated how to make what you want more readable, however.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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'
    
    Login or Signup to reply.
  4. 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))
    
    Login or Signup to reply.
  5. You can make a convenience function for this kind of repeated code (or if you just need it to be more readable, or safer to edit):

    fun <T> T.allEqual(vararg items: T) = items.all { it == this }
    
    // or you could make the receiver the first parameter instead, this is just
    // more explicit about which item is the value being compared against
    1.allEqual(x, y, z)
    

    But no, there isn’t any other shorthand built into the language as far as I’m aware – conditions like x == 1 chained with boolean operators are about as simple as it can get! If you want to check multiple things without repeating yourself, any and all make that easy, while being flexible for all kinds of situations, and allowing the user to put together the functionality they need with those more general functions.

    If you specifically want a version of all that does a simple comparison to a single value, and doesn’t require creating an iterable like listOf, you have to write your own with those tools (which is basically what I’ve done). It’s up to you if you think it’s worth it!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search