Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unused arguments when destructing an object in Kotlin

Tags:

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")
}
like image 674
Trygve Laugstøl Avatar asked Mar 15 '16 11:03

Trygve Laugstøl


2 Answers

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")
}
like image 50
yole Avatar answered Nov 05 '22 22:11

yole


You could use:

val b = makePair().component2()
like image 4
McDowell Avatar answered Nov 05 '22 22:11

McDowell