Michael Lafayette
Michael Lafayette

Reputation: 3072

Scala generic that implements method toIterator

I need a function that will take in an Array, a Map, a List [pretty much any container with a toIterator method], iterate over it, and print its elements.

I tried this:

def method[CollectionT <: TraversableLike[Any, Any]](collection: CollectionT, numElements: Int) {
  val iterator = collection.toIterator
  for(i <- 0 until numElements) {
    if(iterator.hasNext) {
      println(iterator.next()) 
    }
  }
}

^ But it does not work for Array[T]

How do I make a genetic function in Scala that will take in any instance of a class that has a "toIterator: Iterator[A]" method?

Upvotes: 1

Views: 520

Answers (1)

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 59994

A general type that you can use here is GenTraversable:

scala> def printAll(coll: collection.GenTraversable[_]) = coll.foreach(println)
defined function printAll
scala> printAll("aaa")
a
a
a

scala> printAll(Array(1,2,3))
1
2
3

scala> printAll(Seq(4,5,6))
4
5
6

You also don't need an iterator. You can more easily call foreach or use a for comprehension.

Upvotes: 5

Related Questions