Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a byte array in Scala?

Tags:

java

arrays

scala

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) 
like image 950
Hanxue Avatar asked Jun 03 '14 08:06

Hanxue


1 Answers

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}; 
like image 76
Zoltán Avatar answered Sep 29 '22 00:09

Zoltán