Kshitiz Sharma
Kshitiz Sharma

Reputation: 18627

Kotlin: Destructuring in lambda parameters

Is there a way to iterate over a list of objects/pairs like so:

val list = listOf(Pair(1,2),Pair(2,3))

list.forEach { first, second ->
     first + second
}

Following doesn't work either:

list.forEach { (first, second) in it ->
         first + second
}

Upvotes: 4

Views: 820

Answers (1)

marstran
marstran

Reputation: 28056

You can destructure the pair directly in the argument list. You are only missing the parenthesis in your first example.

list.forEach { (first, second) ->
  first + second
}

Upvotes: 9

Related Questions