Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disregard component of a Triple in a comparison

Tags:

tuples

kotlin

I am attempting to compare Triples while disregarding certain values of the Triple. The value I wish to disregard below is signified by _. Note the below code is for example purposes and does not compile because _ is an Unresolved reference.

val coordinates = Triple(3, 2, 5)
when (coordinates) {
    Triple(0, 0, 0) -> println("Origin")
    Triple(_, 0, 0)-> println("On the x-axis.")
    Triple(0, _, 0)-> println("On the y-axis.")
    Triple(0, 0, _)-> println("On the z-axis.")
    else-> println("Somewhere in space")
}

I know you can use _ when destructuring if you would like to ignore a value but that doesn't seem to help me with the above issue:

val (x4, y4, _) = coordinates
println(x4)
println(y4)

Any ideas how I can achieve this?

Thank you!

like image 851
Dick Lucas Avatar asked Dec 05 '25 14:12

Dick Lucas


1 Answers

Underscore for unused variables was introduced in Kotlin 1.1 and it is designed to be used when some variables are not needed in the destructuring declaration.

In the branch conditions of your when expression, Triple(0, 0, 0) is creating an new instance but not destructuring. So, using underscore is not permitted here.

Currently, destructuring in the branch conditions of when expression is not possible in Kotlin. One of the solutions for your case is to compare each of the component verbosely in each branch condition:

val (x, y, z) = Triple(3, 2, 5)
when {
    x == 0 && y == 0 && z == 0 -> println("Origin")
    y == 0 && z == 0 -> println("On the x-axis.")
    x == 0 && z == 0 -> println("On the y-axis.")
    x == 0 && y == 0 -> println("On the z-axis.")
    else -> println("Somewhere in space")
}

Here is a discussion on destructuring in when expression.

like image 120
BakaWaii Avatar answered Dec 07 '25 14:12

BakaWaii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!