问题描述
一个通用方法,可以返回 2 个参数之间的随机整数,就像 ruby 对 rand(0..n)
所做的一样.
A generic method that can return a random integer between 2 parameters like ruby does with rand(0..n)
.
有什么建议吗?
推荐答案
我的建议是扩展 函数在 IntRange 像这样创建随机数:(0..10).random()
My suggestion would be an extension function on IntRange to create randoms like this: (0..10).random()
从 1.3 开始,Kotlin 带有自己的多平台随机生成器.它在这个 KEEP 中有描述.下面描述的扩展现在是Kotlin 标准库的一部分,只需像这样使用它:
As of 1.3, Kotlin comes with its own multi-platform Random generator. It is described in this KEEP. The extension described below is now part of the Kotlin standard library, simply use it like this:
val rnds = (0..10).random() // generated random from 0 to 10 included
科特林 <1.3
在 1.3 之前,在 JVM 上我们使用 Random
甚至 ThreadLocalRandom
如果我们在 JDK 上 >1.6.
Kotlin < 1.3
Before 1.3, on the JVM we use Random
or even ThreadLocalRandom
if we're on JDK > 1.6.
fun IntRange.random() =
Random().nextInt((endInclusive + 1) - start) + start
这样使用:
// will return an `Int` between 0 and 10 (incl.)
(0..10).random()
如果您希望函数仅返回 1, 2, ..., 9
(不包括 10
),请使用由 until
:
If you wanted the function only to return 1, 2, ..., 9
(10
not included), use a range constructed with until
:
(0 until 10).random()
如果您正在使用 JDK >1.6、使用ThreadLocalRandom.current()
而不是 Random()
.
If you're working with JDK > 1.6, use ThreadLocalRandom.current()
instead of Random()
.
KotlinJs 和其他变体
对于 kotlinjs 和其他不允许使用 java.util.Random
的用例,请参阅 这个选择.
For kotlinjs and other use cases which don't allow the usage of java.util.Random
, see this alternative.
此外,请参阅此答案以了解我的建议的变体.它还包括一个随机Char
s 的扩展函数.
Also, see this answer for variations of my suggestion. It also includes an extension function for random Char
s.
这篇关于如何在 Kotlin 中获得随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!