Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a list with lambdas in kotlin

Tags:

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()

like image 218
Killrazor Avatar asked Nov 21 '18 16:11

Killrazor


People also ask

How do I create a list on Kotlin?

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.

How do I make a list string in Kotlin?

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.


1 Answers

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

like image 169
Sergei Rybalkin Avatar answered Sep 18 '22 14:09

Sergei Rybalkin