How to declare a byte array in Scala?
I believe the shortest you can do is
val ipaddr = Array[Byte](192.toByte, 168.toByte, 1, 9)
You have to convert 192
and 168
to bytes because they are not valid byte literals as they are outside the range of signed bytes ([-128, 127]).
Note that the same goes for Java, the following gives a compile error:
byte[] ipaddr = {192, 168, 1, 1};
You have to cast 192 and 168 to bytes:
byte[] ipaddr = {(byte)192, (byte)168, 1, 1};
To expand on Chris Martin's answer, if you're feeling lazy and like you don't want to type out Array(...).map(_.toByte)
over and over again, you can always write a variadic function:
def toBytes(xs: Int*) = xs.map(_.toByte).toArray
Now you can declare your byte array just about as concisely as in Java:
val bytes = toBytes(192, 168, 1, 1) // Array[Byte](-64, -88, 1, 1)