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)
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With