Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure Kotlin objects in streams

Tags:

kotlin

In Scala, I can easily extract values from objects (e.g. tuple) using partial function:

list
    .zip(list.reverse)
    .foreach{case (x, y) => println(s"$x $y")}

How can I do that in Kotlin? It seems that destructors are supported only for assignments and for loops.

like image 841
Željko Trogrlić Avatar asked Mar 13 '23 22:03

Željko Trogrlić


1 Answers

At Kotlin 1.0 use an additional val declaration:

list.foreach{val (x, y) = it; println(s"$x $y")}

The team says they are already working on that feature (the syntax was reserved) and they hopefully will get it in Kotlin 1.1:

list.foreach{(x, y) -> println(s"$x $y")}
like image 178
voddan Avatar answered Mar 23 '23 12:03

voddan