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()
Inside main() , create a variable called numbers of type List<Int> because this will contain a read-only list of integers. Create a new List using the Kotlin standard library function listOf() , and pass in the elements of the list as arguments separated by commas.
To define a list of Strings in Kotlin, call listOf() function and pass all the Strings as arguments to it. listOf() function returns a read-only List. Since, we are passing strings for elements parameter, listOf() function returns a List<String> object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With