4

What could be an alternate way to print the cells of a table other than using a nested loop.

for(i in 1..2){
  for(j in 1..2){
      println("$i,$j")
  }
}

Any approach using Pairs?

2
  • 2
    Using pairs isn’t a better approach because then you’re instantiating a bunch of objects. Commented Jun 15, 2020 at 12:34
  • Yes you are right. Better isn't the right word here, I''ll change it to alternate :P. It's become habitual for me to consider kotlin-ized code better, which is obviously not the case always. Commented Jul 28, 2020 at 14:18

1 Answer 1

3

You can use map/flatMap to convert the ranges to list of Pairs

val pairs = (1..2).flatMap { i -> (1..2).map { j -> i to j } }
pairs.forEach { println("${it.first},${it.second} ") }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That's what I was looking for

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.