Scala:填充一组随机字节

时间:2014-06-17 04:59:56

标签: arrays scala

这是我目前使用的代码

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]作为参数,而不是返回单个字节。

2 个答案:

答案 0 :(得分:9)

手动操作怎么样? 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)

答案 1 :(得分:6)

Kestrel combinator

def kestrel[A](x: A)(f: A => Unit): A = { f(x); x }

有了它,你可以写:

sendAndReceive(kestrel(Array.fill[Byte](20)(0))(Random.nextBytes))
相关问题