top | item 41386949

(no title)

rbehrends | 1 year ago

Like this?

  sequence { for (x in 0..<10) for (y in 0..<10) yield(x*y) }.toList()
Now, technically, Kotlin doesn't have list comprehensions, only the equivalent of generator expressions in Python, so you have to tack an extra `.toList()` on at the end if you want a list, but you can write pretty much any for comprehension in Python in a similar way in Kotlin.

On the other hand, you're not limited to for loops/ifs inside such a generator, but can use fairly arbitrary control flow.

discuss

order

robch|1 year ago

You could also build the list directly.

  buildList { for (x in 0..<10) for (y in 0..<10) add(x*y) }