user3587213
user3587213

Reputation: 13

Function that takes any collection as argument Scala

I've been trying to write a function, that takes any collection that inherits Seq trait and performs action on it. I've come up with this:

def printAll[A, B <: Seq[A]] (xs: B) = {
  xs foreach println
} 

But this function works only with such arguments:

printAll(Seq.empty)
printAll(List())

etc. How can I improve it to work in this way for example:

printAll(List(1,2,3)) // scala> 1 2 3

Upvotes: 1

Views: 109

Answers (1)

Giovanni Caporaletti
Giovanni Caporaletti

Reputation: 5556

if your goal is to take any collection that inherits (or is viewable as) a Seq, you can just do that:

  def printAll[A](xs: Seq[A]) = {
     xs foreach println
  }

using your version you have to give the type inferencer a hint:

printAll[Int, List[Int]](List(1, 2, 3))

Upvotes: 2

Related Questions