在Kotlin中生成带有Lambda的列表 [英] Generate a list with lambdas in kotlin
问题描述
我是Kotlin和lambdas的新手,我正试图了解它.我正在尝试生成100个随机数的列表. 这有效:
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()
但是这不起作用.我试图弄清楚如何使用在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()
推荐答案
使用kotlin.collections
函数执行此操作更好:
It's way better to use kotlin.collections
function to do this:
List(100) {
Random.nextInt()
}
根据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() }
不能使用forEach
的原因是它返回Unit
(在Java,C#等中类似于void
). map
操作Iterable
(在这种情况下为1至100的数字range
)将它们映射为另一个值.然后,它将返回包含所有这些值的列表.在这种情况下,使用上面的List
构造函数更有意义,因为您并不是真正地映射"值,而是创建一个列表
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
这篇关于在Kotlin中生成带有Lambda的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!