这是我目前使用的代码
val bytes = new Array[Byte](20)
scala.util.Random.nextBytes(bytes)
sendAndReceive(bytes)
有没有办法把它变成单线?例如,如果它是一个整数数组,我可以做
sendAndReceive(Array.fill(20){scala.util.Random.nextInt(9)}
更换
nextInt
与 nextBytes
不起作用,因为 nextBytes 需要 Array[Byte]
作为参数,而不是返回单个字节。
最佳答案
手动做呢? Byte
范围是从 -128 到 127。这给了我们:
Array.fill(20)((scala.util.Random.nextInt(256) - 128).toByte)
如果您在多个地方需要它,您也可以编写一个隐式。
implicit class ExtendedRandom(ran: scala.util.Random) {
def nextByte = (ran.nextInt(256) - 128).toByte
}
Array.fill(20)(scala.util.Random.nextByte)
正如@Chris Martin 所建议的,您也可以使用
nextBytes
在隐式类中。implicit class ExtendedRandom(ran: scala.util.Random) {
def nextByteArray(size: Int) = {
val arr = new Array[Byte](size)
ran.nextBytes(arr)
arr
}
}
scala.util.Random.nextByteArray(20)
关于arrays - Scala:填充随机字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24256015/