Scala-创建指定长度的类型参数化数组 [英] Scala - creating a type parametrized array of specified length
问题描述
如果在Scala IDE中,请尝试以下操作:
If in Scala IDE try the following:
val chars = Array[Char](256)
一切都很好.但是,如果我这样做:
it is all fine. But if I do this:
val len = 256
val chars = Array[Char](len)
它说它期望一个Char
而不是len
吗?为什么?我希望行为是一样的!为什么它认为我要把那个东西放到数组中而不是指定它的大小?据我所知,没有用于数组的构造函数,只需一个参数即可将其放置在数组中.
it says that it expects a Char
instead of len
? Why? I expect the behavior to be the same! Why does it think that I want to put that thing in the array instead of specifying it's size? As far as I know, there is no constructor for arrays that takes a single argument to place it inside the array.
推荐答案
val chars = Array[Char](256)
之所以有效,是因为256被视为Char
,它会创建一个元素数组(代码为256)
This works because 256 treated as a Char
and it creates one-element array (with code 256)
val len = 256
val chars = Array[Char](len)
这里len是Int
,所以失败了
Here len is Int
, so it fails
要创建指定大小的数组,您需要像这样的
To create array of specified size you need something like this
val chars = Array.fill(256){0}
其中{0}
是产生元素的函数
如果数组的内容无关紧要,您也可以使用new
代替fill
:
If the contents of the Array don't matter you can also use new
instead of fill
:
val chars = new Array[Char](256)
这篇关于Scala-创建指定长度的类型参数化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!