Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to write nested loops in functional way?

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?

like image 673
Vandit Goel Avatar asked Oct 25 '25 01:10

Vandit Goel


1 Answers

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} ") }
like image 162
sidgate Avatar answered Oct 28 '25 01:10

sidgate