Trygve Laugstøl
Trygve Laugstøl

Reputation: 7726

Unused arguments when destructing an object in Kotlin

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")
}

Upvotes: 8

Views: 434

Answers (3)

yole
yole

Reputation: 97268

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")
}

Upvotes: 10

Kirill Rakhman
Kirill Rakhman

Reputation: 43851

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")
}

Upvotes: 0

McDowell
McDowell

Reputation: 108959

You could use:

val b = makePair().component2()

Upvotes: 4

Related Questions