Generate a list with lambdas in kotlin

It’s way better to use kotlin.collections function to do this:

List(100) {
    Random.nextInt()
}

According to Collections.kt

inline fun <T> List(size: Int, init: (index: Int) -> T): List<T> = MutableList(size, init)

It’s also possible to generate using range like in your case:

(1..100).map { Random.nextInt() }

The reason you can’t use forEach is that it return Unit (which is sort of like void in Java, C#, etc.). map operates Iterable (in this case the range of numbers from 1 to 100) to map them to a different value. It then returns a list with all those values. In this case, it makes more sense to use the List constructor above because you’re not really “mapping” the values, but creating a list

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)