I'm trying to work with destructuring. It seems p...
# getting-started
c
I'm trying to work with destructuring. It seems pretty limited. Is there a cleaner way of doing this?
Copy code
class Foo {
  private val numbers : Int
  private val letters : Int
  init {
      val (c1, c2) = readMultiple()
      numbers = c1
      letters = c2
  }
}
h
Currently not, but there's work ongoing to allow name based destructuring instead: https://youtrack.jetbrains.com/issue/KT-19627 I'd probably not use it currently (unless in really small projects) because the position based destructuring is prone to cause errors when the result changes in a type-compatible but semantics changing way. For example, if someone changes the
readMultiple()
method in your example to swap the results in the output, your class would produce false results without the compiler even warning you.
v
Maybe you like this better:
Copy code
readMultiple().also { (c1, c2) ->
    numbers = c1
    letters = c2
}
👍 2
c
That is a little cleaner, if still a bit wordy.
v
Yeah, in Groovy you could do
(numbers, letters) = readMultiple()
, but Kotlin does not like that Syntax
k
Another possibility:
Copy code
class Foo {
  private val multiple = readMultiple()
  private val numbers get() = multiple.first
  private val letters get() = multiple.second
}
v
Only if it is a
Pair
, otherwise
.component1()
and
.component2()
🙂
k
Or a triple 😛.
1