How to declare a byte array in Scala?

2020-02-17 06:31发布

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)

7条回答
欢心
2楼-- · 2020-02-17 07:14

split on a String could do the trick:

val ipaddr: Array[Byte] = 
  "192.168.1.1".split('.').map(_.toInt).map(_.toByte)    

Breaking this down we have

"192.168.1.1"
  .split('.')    // Array[String]("192", "168", "1", "1")
  .map(_.toInt)  // Array[Int](192, 168, 1, 1)
  .map(_.toByte) // Array[Byte](-64, -88, 1, 1)    
查看更多
登录 后发表回答