我有带有foreach方法的案例类:
case class Sequence[A](initialElems: A*) {
private val elems = ArrayBuffer[A]()
elems ++= initialElems
@tailrec
final def foreach(block: A => Unit, elems: ArrayBuffer[A] = elems): Unit = elems.size match {
case 0 =>
case _ =>
block(elems.head)
foreach(block, elems.tail)
}
}
但是我觉得很奇怪,还有另一种更简单有效的书写方式吗?
答案 0 :(得分:1)
目前尚不清楚为什么可以使用现有的foreach
方法时完全想要递归函数:
case class Sequence[A](initialElems: A*) {
private val elems = ArrayBuffer[A](initialElems:_*)
final def foreach(block: A => Unit, elems: ArrayBuffer[A] = elems): Unit =
elems.foreach(block)
}
能够传递elems
值也很奇怪。如果您确实传递了一个值,则此方法不使用任何类数据,这意味着它实际上并不需要成为一个方法。
最后,通常将block
作为最终参数组,以便可以更自然地使用它,如下所示:
case class Sequence[A](initialElems: A*) {
private val elems = ArrayBuffer[A](initialElems:_*)
final def foreach(elems: ArrayBuffer[A])(block: A => Unit): Unit = elems.foreach(block)
final def foreach(block: A => Unit): Unit = elems.foreach(block)
}
val s = Sequence(1,2,3)
s.foreach{ e =>
println(e)
}