A. Gisbert
A. Gisbert

Reputation: 163

Scala-Is there another way to write this foreach method?

I have this case class with the foreach method:

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)
  }
}

But it feels weird to me, is there another, more simple and efficient way to write it?

Upvotes: 2

Views: 238

Answers (1)

Tim
Tim

Reputation: 27421

It is not clear why you want a recursive function at all when you can use the existing foreach method:

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)
}

It is also odd to be able to pass in the elems value. If you do pass in a value then this method does not use any of the class data, which means it doesn't really need to be a method.

Finally, it is usual to put the block as the final parameter group so that it can be used in a more natural way, like this:

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)
}

Upvotes: 2

Related Questions