Killrazor
Killrazor

Reputation: 7184

Generate a list with lambdas in kotlin

I'm new to Kotlin and lambdas and I'm trying to understand it. I'm trying to generate a list of 100 random numbers. This works:

private val maxRandomValues = (1..100).toList()

But I want to do something like that:

private val maxRandomValues = (1..100).forEach { RandomGenerator().nextDouble() }.toList()

But this is not working. I'm trying to figure out how to use the values generated into forEach are used in the toList()

Upvotes: 35

Views: 28144

Answers (2)

Xuan
Xuan

Reputation: 746

Beside using constructor: List(10, { Random.nextInt() }), Kotlin also has a built-in function for this purpose: buildList { repeat(10) { add(Random.nextInt()) } }

See: https://kotlinlang.org/docs/constructing-collections.html

Upvotes: 2

Sergei Rybalkin
Sergei Rybalkin

Reputation: 3453

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

Upvotes: 59

Related Questions