How to declare a byte array in Scala?

前端 未结 7 1295
心在旅途
心在旅途 2020-12-23 21:22

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 verbo

7条回答
  •  攒了一身酷
    2020-12-23 22:06

    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)    
    

提交回复
热议问题