【发布时间】:2010-11-17 11:45:54
【问题描述】:
有几种方法可以在 Scala 中构造不可变列表(请参阅下面的人为示例代码)。您可以使用可变的 ListBuffer,创建一个 var 列表并对其进行修改,使用 tail recursive 方法,可能还有其他我不知道的方法。
本能地,我使用 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)
}
【问题讨论】:
标签: scala