谁能详细解释此功能的作用以及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 += i)
})
l.toList
}
答案 0 :(得分:1)
ListBuffer.empty[Int]
用于实例化ListBuffer
ListBuffer.empty[Int]
与ListBuffer[Int]()
ListBuffer
是可变列表。
i
。num
次i
被添加到列表缓冲区稍后使用toList
调用将可变列表转换为不可变列表
那是
arr
列表的每个值被添加到列表缓冲区num
次
# 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)