Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Filling an Array of Random Bytes

Tags:

arrays

scala

This is the code that I currently use

val bytes = new Array[Byte](20)
scala.util.Random.nextBytes(bytes)
sendAndReceive(bytes)

Is there a way to turn that into a one-liner? For example, if it is an Integer array I can do

sendAndReceive(Array.fill(20){scala.util.Random.nextInt(9)}

Replacing nextInt with nextBytes does not work because nextBytes takes an Array[Byte] as parameter, instead of returning a single Byte.

like image 448
Hanxue Avatar asked Dec 05 '22 06:12

Hanxue


2 Answers

How about manually doing it? Byte range is from -128 to 127. That gives us:

Array.fill(20)((scala.util.Random.nextInt(256) - 128).toByte)

You can also write an implicit if you need it at multiple places.

implicit class ExtendedRandom(ran: scala.util.Random) {
  def nextByte = (ran.nextInt(256) - 128).toByte
}

Array.fill(20)(scala.util.Random.nextByte)

As @Chris Martin suggested, you can also use nextBytes in an implicit class.

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)
like image 91
Kigyo Avatar answered Dec 17 '22 10:12

Kigyo


There's the Kestrel combinator:

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

With it you can write:

sendAndReceive(kestrel(Array.fill[Byte](20)(0))(Random.nextBytes))
like image 32
Chris Martin Avatar answered Dec 17 '22 11:12

Chris Martin