如何在 Kotlin 中获取随机数? [英] How can I get a random number in Kotlin?

查看:21
本文介绍了如何在 Kotlin 中获取随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个可以返回两个参数之间的随机整数的通用方法,就像 ruby​​ 对 rand(0..n) 所做的那样.

A generic method that can return a random integer between 2 parameters like ruby does with rand(0..n).

有什么建议吗?

推荐答案

我的建议是一个 extensionIntRange 函数> 像这样创建随机数:(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 甚至如果我们在 JDK 上使用 ThreadLocalRandom >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 和其他变体

对于 kotlinjs 和其他不允许使用 java.util.Random 的用例,请参阅 这个替代方案.

For kotlinjs and other use cases which don't allow the usage of java.util.Random, see this alternative.

另外,请参阅此答案了解我的建议的变体.它还包括随机 Chars 的扩展功能.

Also, see this answer for variations of my suggestion. It also includes an extension function for random Chars.

这篇关于如何在 Kotlin 中获取随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆