6

Probably this question should go the authors of Kotlin, but I'm sure that on SO there are many Kotlin users with deep knowledge of its architecture.

So my question is: why the language doesn't support destructuring in when expressions?

For example I would like to have the following code:

data class Person(val name: String, val age: Int)

when (person) {
    ("John", _) -> print("It is John") //it won't compile
    else -> print("It's not John")
}

As destructuring uses the component1, component2, etc. methods I'm curious why this simple value comparison can't be used as shown above. Is the problem in modification of when mechanism or the destructing itself?

Jakub Licznerski
  • 1,008
  • 1
  • 17
  • 33

1 Answers1

7

There's an open feature ticket for that:

KT-20004: Scala-like constructor pattern matching in when statement

Also, Java is going to support data classes and pattern matching in the near future, which might have an impact on the implementation of the Kotlin version.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • Taking your assumption into consideration would it imply targeting the new version of Java in Kotlin in order to use this new feature? Or is it possible the new feature could be compiled to older versions? The article does not mention compatibility. – Jakub Licznerski Jan 18 '18 at 17:18
  • 1
    There will most probably be a version regardless of that newer Java version, too. – s1m0nw1 Jan 18 '18 at 17:19
  • Thanks! I really like Kotlin's simplicity but I think there are a few features (like this) which could be excerpted e.g. from Scala without impact on performance and clarity of the language. – Jakub Licznerski Jan 18 '18 at 17:22
  • But Scala‘s pattern matching is often called “too complex”, that’s probably a reason for having it kept out of the language in the first place – s1m0nw1 Jan 18 '18 at 17:23