有多种方法可以在Scala中构造不可变列表(请参见下面的伪造示例代码)。您可以使用可变的ListBuffer,创建var列表并对其进行修改,使用尾部递归方法以及其他我不知道的方法。
本能地,我使用ListBuffer,但是我没有充分的理由这样做。是否有一种首选的或惯用的方法来创建列表,或者是否存在最适合一种方法而不是另一种方法的情况?
import scala.collection.mutable.ListBuffer
// THESE are all the same as: 0 to 3 toList.
def listTestA() ={
    var list:List[Int] = Nil
    for(i <- 0 to 3) 
        list = list ::: List(i)
    list
}
def listTestB() ={
    val list = new ListBuffer[Int]()
    for (i <- 0 to 3) 
        list += i
    list.toList
}
def listTestC() ={
    def _add(l:List[Int], i:Int):List[Int] = i match {
        case 3 => l ::: List(3)
        case _ => _add(l ::: List(i), i +1)
    }
    _add(Nil, 0)
}
          
What you DON'T do is use a List and append to it那是因为创建了新列表吗?而使用前置操作将不会创建新列表?