In Scala, I can declare a byte array this way
val ipaddr: Array[Byte] = Array(192.toByte, 168.toByte, 1.toByte, 9.toByte)
This is too verbose. Is there a simpler way to declare a Byte array, similar to Java's
byte[] ipaddr = {192, 168, 1, 1};
Note that the following results in an error due to the .
in the String
InetAddress.getByAddress("192.168.1.1".toByte)
How about
Array(192, 168, 1, 1).map(_.toByte)
?I believe the shortest you can do is
You have to convert
192
and168
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:
You have to cast 192 and 168 to bytes:
For your specific example you could simply use
InetAddress.getByName
instead:In general Didier is right,
Byte
s are -128 to 127, so this works:but this doesn't:
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:Now you can declare your byte array just about as concisely as in Java:
You can use implicit
And that will convert all Int values in scope in places where byte is required.
By adding methods to
StringContext
one can easily define various methods for converting String literals into Byte arrays. For example, we can do this:or this:
Notice that it is especially useful for working with byte arrays in hexadecimal notation, because writing out the "0x" prefix in front of every byte can become very annoying very quickly, as can be seen in this example. When using hexadecimal notation as in
Array(0xAB, 0xCD, 0xEF).map(_.toByte)
, it's not the call tomap
that is awkward, it's the repeated "0x"-prefix that generates all the noise.Here is a little code snippet that shows how several different ways for byte array creation could be implemented by providing an
implicit class
that wraps aStringContext
:As soon as this class is in the implicit scope, we can use all of the following notations to define byte arrays:
Note that the string literals can also contain references to variables using the
$varargVar
syntax inside of the string. All examples generate the same byte array[C0,A8,01,0F]
.On performance: all of the above is build around method calls, the literals are not transformed to byte-arrays at compile time.