如何在Kotlin中获得随机数? [英] How can I get a random number in Kotlin?
问题描述
一个泛型方法,可以返回2个参数之间的随机整数,如ruby与 rand(0..n)
。
A generic method that can return a random integer between 2 parameters like ruby does with rand(0..n)
.
有什么建议吗?
推荐答案
我的建议是扩展功能-range / index.htmlrel =nofollow noreferrer> IntRange 创建这样的randoms:(0..10).random()
My suggestion would be an extension function on IntRange to create randoms like this: (0..10).random()
从1.3开始,Kotlin自带多平台随机生成器。在 KEEP 中对此进行了描述。您现在可以执行以下操作(来源):
As of 1.3, Kotlin comes with its own multiplatform Random generator. It is described in this KEEP. You can now do the following (source):
Random.nextInt(0, 10)
在所有平台上,扩展功能如下所示:
The extension function can hereby look like the following on all platforms:
fun IntRange.random() = Random.nextInt(start, endInclusive + 1)
< h2> Kotlin< 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
不包括在内),使用由 直到
:
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和其他不允许使用 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中获得随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!