如何创建具有相同元素n次的列表?
手动执行:
scala> def times(n: Int, s: String) =
| (for(i <- 1 to n) yield s).toList
times: (n: Int, s: String)List[String]
scala> times(3, "foo")
res4: List[String] = List(foo, foo, foo)
Run Code Online (Sandbox Code Playgroud)
还有内置的方法来做同样的事情吗?
kir*_*uku 152
见scala.collection.generic.SeqFactory.fill(正的:int)(ELEM:=> A)该集合的数据结构,例如Seq,Stream,Iterator等等,延伸:
scala> List.fill(3)("foo")
res1: List[String] = List(foo, foo, foo)
Run Code Online (Sandbox Code Playgroud)
警告 Scala 2.7中不提供此功能.
| 归档时间: |
|
| 查看次数: |
41597 次 |
| 最近记录: |