How to declare a byte array in Scala?

arrays, java, scala

Solution

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};

Problem

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) ```

Original source

Related problems