Scala - 创建指定长度的类型参数化数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9413507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala - creating a type parametrized array of specified length
提问by noncom
If in Scala IDE try the following:
如果在 Scala IDE 中尝试以下操作:
val chars = Array[Char](256)
it is all fine. But if I do this:
一切都很好。但如果我这样做:
val len = 256
val chars = Array[Char](len)
it says that it expects a Charinstead 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.
它说它期望一个Char而不是len?为什么?我希望行为是相同的!为什么它认为我想把那个东西放在数组中而不是指定它的大小?据我所知,没有数组的构造函数可以使用单个参数将其放置在数组中。
回答by Sergey Passichenko
val chars = Array[Char](256)
This works because 256 treated as a Charand it creates one-element array (with code 256)
这是有效的,因为 256 被视为 aChar并且它创建了一个元素数组(代码为 256)
val len = 256
val chars = Array[Char](len)
Here len is Int, so it fails
这是 len Int,所以它失败了
To create array of specified size you need something like this
要创建指定大小的数组,您需要这样的东西
val chars = Array.fill(256){0}
where {0}is a function to produce elements
哪里{0}是产生元素的函数
If the contents of the Array don't matter you can also use newinstead of fill:
如果数组的内容无关紧要,您也可以使用new代替fill:
val chars = new Array[Char](256)

