8

When destructuring an object, is it possible to only declare the variables I need?

In this example I'm only using b and my IDE is giving me a warning that a is unused.

fun run() {
    fun makePair() = Pair("Apple", "Orange")

    val (a, b) = makePair()

    println("b = $b")
}
Trygve Laugstøl
  • 7,440
  • 2
  • 36
  • 40
  • In other languages, you often have something like `val (_, b) = makePair()`. Nothing similar in Kotlin? – Thilo Mar 15 '16 at 11:54
  • Somewhat similar question, and somewhat unsatisfactory answer: http://stackoverflow.com/questions/29046636/mark-unused-parameters-in-kotlin – Thilo Mar 15 '16 at 11:57
  • @Thilo Scala has it, but doesn't seem like there is anything like it in Kotlin. At least not yet. – Trygve Laugstøl Mar 15 '16 at 13:55

3 Answers3

10

Since Kotlin 1.1, you can use an underscore to mark an unused component of a destructing declaration:

fun run() {
    fun makePair() = Pair("Apple", "Orange")

    val (_, b) = makePair()

    println("b = $b")
}
yole
  • 92,896
  • 20
  • 260
  • 197
4

You could use:

val b = makePair().component2()
McDowell
  • 107,573
  • 31
  • 204
  • 267
0

If you're only interested in the first couple of arguments you can omit the remaining ones. In your code that's not possible, but if you change the order of arguments, you can write it this way:

fun run() {
    fun makePair() = Pair("Orange", "Apple")

    val (b) = makePair()

    println("b = $b")
}
Kirill Rakhman
  • 42,195
  • 18
  • 124
  • 148