有几种方法可以在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 …Run Code Online (Sandbox Code Playgroud) scala ×1