Kotlin Random.Default用法及代码示例

177 阅读1分钟

本文方法及代码示例基于 Kotlin 2.1.20 Released

Random.Default 所在包 kotlin.random.Random.Default,其相关用法介绍如下:

用法:

companion object Default : Random, Serializable

默认随机数生成器。

在 JVM 上,这个生成器是线程安全的,它的方法可以从多个线程中调用。

代码示例:

import kotlin.math.sin
import kotlin.random.Random
import kotlin.test.assertTrue

fun main(args: Array<String>) {
    //sampleStart
    val randomValues = List(10) { Random.nextInt(0, 100) }
    // prints new sequence every time
    println(randomValues)

    val nextValues = List(10) { Random.nextInt(0, 100) }
    println(nextValues)
    println("randomValues != nextValues is ${randomValues != nextValues}") // true
    //sampleEnd
}

// 输出
[63, 94, 85, 15, 93, 45, 19, 57, 39, 48]
[9, 15, 79, 3, 74, 61, 64, 78, 67, 22]
randomValues != nextValues is true

相关方法