Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala中的列表建筑_Scala_List - Fatal编程技术网

Scala中的列表建筑

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 +=

有人能详细解释一下这个函数在做什么,以及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
}

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


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

ListBuffer
是可变列表

  • 对于arr列表的每个值
    i
  • 我是印刷品
  • num
    times
    i
    被添加到列表缓冲区
  • 稍后,使用
    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)