Scala 创建列表[Int]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2514438/
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 create List[Int]
提问by Don Ch
How can I quickly create a List[Int]that has 1 to 100 in it?
如何快速创建一个List[Int]包含 1 到 100 的内容?
I tried List(0 to 100), but it returns List[Range.Inclusive]
我试过了List(0 to 100),但它回来了List[Range.Inclusive]
Thanks
谢谢
回答by Ben Lings
Try
尝试
(0 to 100).toList
The code you tried is creating a list with a single element - the range. You might also be able to do
您尝试的代码是创建一个包含单个元素的列表 - 范围。你也可以这样做
List(0 to 100:_*)
Edit
编辑
The List(...)call takes a variable number of parameters (xs: A*). Unlike varargs in Java, even if you pass a Seqas a parameter (a Rangeis a Seq), it will still treat it as the first element in the varargs parameter. The :_*says "treat this parameter as the entire varargs Seq, not just the first element".
该List(...)调用采用可变数量的参数 ( xs: A*)。与 Java 中的 varargs 不同,即使您将 aSeq作为参数传递(aRange是 a Seq),它仍然会将其视为 varargs 参数中的第一个元素。该:_*说“作为整个可变参数对待这个参数Seq,而不仅仅是第一要素”。
If you read : A*as "an (:) 'A' (A) repeated (*)", you can think of :_*as "as (:) 'something' (_) repeated (*)"
如果读: A*作“an ( :) 'A' ( A) 重复 ( *)”,则可以认为:_*是“作为 ( :) '某物' ( _) 重复 ( *)”
回答by Eastsun
List.range(1,101)
The second argument is exclusive so this produces a list from 1 to 100.
第二个参数是独占的,所以这会产生一个从 1 到 100 的列表。

