Daniel Sobral 先生在这里回答说Nil
不能用作fold
.
不能Nil
用作初始累加器值
scala> xs
res9: List[Int] = List(1, 2, 3)
scala> xs.foldLeft(Nil)( (acc, elem) => elem.toString :: acc)
<console>:9: error: type mismatch;
found : List[String]
required: scala.collection.immutable.Nil.type
xs.foldLeft(Nil)( (acc, elem) => elem.toString :: acc)
但如果我通过它会起作用List[String]()
。
scala> xs.foldLeft(List[String]())( (acc, elem) => elem.toString :: acc)
res7: List[String] = List(3, 2, 1)
但是为什么我可以Nil
在下面的尾递归函数中使用呢?
scala> def toStringList(as: List[Int]): List[String] = {
| def go(bs: List[Int], acc: List[String]): List[String]= bs match {
| case Nil => acc
| case x :: xs => go(xs, x.toString :: acc)
| }
| println(as)
| go(as, Nil)
| }
toStringList: (as: List[Int])List[String]