I can generate a random sequence of numbers in a certain range like the following:

fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) +  start
fun generateRandomNumberList(len: Int, low: Int = 0, high: Int = 255): List<Int> {
  (0..len-1).map {
    (low..high).random()
  }.toList()
}

然后我必须用以下方法延长List次:

fun List<Char>.random() = this[Random().nextInt(this.size)]

然后我可以做:

fun generateRandomString(len: Int = 15): String{
  val alphanumerics = CharArray(26) { it -> (it + 97).toChar() }.toSet()
      .union(CharArray(9) { it -> (it + 48).toChar() }.toSet())
  return (0..len-1).map {
      alphanumerics.toList().random()
  }.joinToString("")
}

但也许有更好的办法?

推荐答案

Assuming you have a specific set of source characters (source in this snippet), you could do this:

val source = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
java.util.Random().ints(outputStrLength, 0, source.length)
        .asSequence()
        .map(source::get)
        .joinToString("")

Which gives strings like "LYANFGNPNI" for outputStrLength = 10.

两个重要的位是

  1. Random().ints(length, minValue, maxValue)产生length个随机数的流,每个随机数从minValuemaxValue-1,以及
  2. asSequence()将不太有用的IntStream转换成更有用的Sequence<Int>.

Kotlin相关问答推荐

在Kotlin Jetpack中重用下拉菜单

Jetpack Compose中的数字 Select 器问题

如何在Jetpack Compose中从领域查询中读取数据?

两个LocalDateTime之间的Kotlin差异

在 Kotlin 中,为什么我们要在闭包中捕获值

Kotlin 基于参数类型的返回类型推断

为什么会出现Kotlin.Unit错误以及如何修复它?

按钮无法在 Android Studio 上打开新活动

在 Kotlin 中,如何绑定扩展方法以在接收器范围函数中工作

每个 Kotlin 版本的默认 Kotlin 语言版本是什么?

如何有效地填充 Gradle Kotlin DSL 中的额外属性?

Kotlin 协程中的 Dispatchers.Main 和 Dispatchers.Default 有什么区别?

Android Room - error: Cannot figure out how to save this field into database

是否在Kotlin中重写enum toString()?

在Kotlin中使用@Service时引发异常

如何序列化/反序列化Kotlin密封类?

Kotlin out-projected 类型禁止使用

使用 kotlin 每 3 位数添加逗号或点

如何在 firebase 数据库中使用 kotlin 协程

Kotlin - 为什么我会得到 KotlinNullPointerException