What's the most idiomatic way to match on the type...
# getting-started
s
What's the most idiomatic way to match on the type of multiple expressions? e.g.
Copy code
class A
class B : A
class C : A

class X
class Y : X
class Z : X

fun example(a : A, x : X) = when(a, x) {
  is B, is Y -> "B and Y"
  is C, is Z -> "C and Z"
  else -> "Not an interesting case"
}
u
Try something like this
Copy code
when {
  a is B && x is Y -> "B and Y"
  a is C && x is Z -> "C and Z"
}
s
That's what I ended up going with but it doesn't provide exhaustiveness checking
u
If you want exhaustive check on multiple variables, you must use sealed classes and nested when checks:
Copy code
sealed class A
class B : A()
class C : A()

sealed class X
class Y : X()
class Z : X()

fun example(a: A, x: X) = when (a) {
    is B -> when (x) {
        is Y -> "B and Y"
        is Z -> "B and Z"
    }
    is C -> when (x) {
        is Y -> "C and Y"
        is Z -> "C and Z"
    }
}