清单建筑在斯卡拉

时间:2018-07-07 07:50:20

标签: 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 += i)
  })

  l.toList
}

1 个答案:

答案 0 :(得分:1)

ListBuffer.empty[Int]用于实例化ListBuffer

ListBuffer.empty[Int]ListBuffer[Int]()

ListBuffer是可变列表。

  1. 对于arr列表的每个值i
  2. 我已打印
  3. numi被添加到列表缓冲区

稍后使用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)