Scala中的列表建筑
有人能详细解释一下这个函数在做什么,以及scala.collection.mutable.ListBuffer.empty[Int]的用途吗Scala中的列表建筑,scala,list,Scala,List,有人能详细解释一下这个函数在做什么,以及scala.collection.mutable.ListBuffer.empty[Int]的用途吗 def f(num: Int, arr: List[Int]): List[Int] = { val l = scala.collection.mutable.ListBuffer.empty[Int] arr.foreach(i => { println(i) (1 to num).foreach(_ => l +=
def f(num: Int, arr: List[Int]): List[Int] = {
val l = scala.collection.mutable.ListBuffer.empty[Int]
arr.foreach(i => {
println(i)
(1 to num).foreach(_ => l += i)
})
l.toList
}
ListBuffer.empty[Int]
用于实例化ListBuffer
ListBuffer.empty[Int]
与ListBuffer[Int]()
ListBuffer
是可变列表
i
num
timesi
被添加到列表缓冲区toList
调用将可变列表转换为不可变列表
这意味着
arr
list的每个值都被添加到列表缓冲区num
次
你的问题不清楚。为什么它被贴上了标签?这与容错有什么关系?感谢Pamu,现在对我来说很有意义,可以分享一些关于如何通过从用户获取元素来构建列表的想法?@rupshkumar
list(elementFromUser)
或者你可以使用elementFromUser::Nil
# Scala REPL
scala> :paste
// Entering paste mode (ctrl-D to finish)
def f(num: Int, arr: List[Int]): List[Int] = {
val l = scala.collection.mutable.ListBuffer.empty[Int]
arr.foreach(i => {
println(i)
(1 to num).foreach(_ => l += i)
})
l.toList
}
// Exiting paste mode, now interpreting.
f: (num: Int, arr: List[Int])List[Int]
scala> f(10, (1 to 10).toList)
1
2
3
4
5
6
7
8
9
10
res2: List[Int] = List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10)