How to declare a byte array in Scala?

前端 未结 7 1296
心在旅途
心在旅途 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:04

    To expand on Chris Martin's answer, if you're feeling lazy and like you don't want to type out Array(...).map(_.toByte) over and over again, you can always write a variadic function:

    def toBytes(xs: Int*) = xs.map(_.toByte).toArray
    

    Now you can declare your byte array just about as concisely as in Java:

    val bytes = toBytes(192, 168, 1, 1) // Array[Byte](-64, -88, 1, 1)
    

提交回复
热议问题