如何在Scala中声明一个字节数组? [英] How to declare a byte array in Scala?

查看:384
本文介绍了如何在Scala中声明一个字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,我可以用这种方式声明一个字节数组

In Scala, I can declare a byte array this way

val ipaddr: Array[Byte] = Array(192.toByte, 168.toByte, 1.toByte, 9.toByte)

这太详细了。是否有更简单的方法来声明Byte数组,类似于Java的

This is too verbose. Is there a simpler way to declare a Byte array, similar to Java's

byte[] ipaddr = {192, 168, 1, 1};

请注意,由于,以下内容会导致错误。

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)

必须转换 192 168 到字节,因为它们不是有效的字节文字,因为它们超出了有符号字节的范围([-128,127])。

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]).

注意同样的情况对于Java,下面给出了编译错误:

Note that the same goes for Java, the following gives a compile error:

byte[] ipaddr = {192, 168, 1, 1};

您必须将192和168转换为字节:

You have to cast 192 and 168 to bytes:

byte[] ipaddr = {(byte)192, (byte)168, 1, 1};

这篇关于如何在Scala中声明一个字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆