蘇哲聖
蘇哲聖

Reputation: 795

How to append an element to an Iterator in scala

I want to append an element to the end of an iterator like this:

val a = Iterator(3, 4)
val b = a + 5 // expect b == Iterator(3,4,5), but there is no + method
val b2 = a ++ Iterator(5) // That works, but not concise.

Is there a better way than b2 to make this?

Upvotes: 2

Views: 3826

Answers (1)

jwvh
jwvh

Reputation: 51271

You can always just hide the not-concise syntax behind something that you like better.

implicit class IterPlus[A](itr: Iterator[A]) {
  def +(elem: A) = itr ++ Iterator(elem)
}

val a = Iterator(3, 4)
val b = a + 5          //Iterator(3, 4, 5)

Upvotes: 2

Related Questions