5

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
}

1 Answer 1

9

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.