Use Kotlin's `when` to pattern-match against an empty array?

Viewed 54

Given a is an array, I'd like to use pattern matching to find out whether a's an empty array. From other functional languages, I would assume that there exists some literal, e.g., [], that represents an empty array, and I can just match against it, like so:

val a: Array<Int> = ...

when (a) {
    []   -> println("empty")
    else -> println("not empty")
}

Is this possible in Kotlin?

1 Answers

There are two types of when expression.

  • when with a subject (which is in parentheses) can only be used with branches where the conditions are implicit ==, in/!in something, or is/!is something.
  • when without a subject allows each branch to be an arbitrary conditional.

The problem with arrays is that they have no useful == check. arrayOf(1) == arrayOf(1) will evaluate to false because they aren't the same array instance. This is one of several reasons you should usually prefer Lists to Arrays.

So, to handle an empty array, you have to use when without a subject:

when {
    a.isEmpty() -> println("empty")
    else -> println("not empty")
}

or in this particular case, you could move the empty check into the subject:

when (a.isEmpty()) {
    true -> println("empty")
    false -> println("not empty")
}
Related