Scala generic method. Accept any sequence of nummerical values

493 views Asked by At

Can I make a function in Scala accept both Vectors and Lists without specifying the concrete type value?

I've now got something like this:

def testFunc[V <: Seq[Int]](x: V) = x

testFunc(List(1, 3)) // res0: List[Int] = List(1, 3)
testFunc(Vector(1, 3)) // res1: scala.collection.immutable.Vector[Int] = Vector(1, 3)

How can I modify this functions so it also accepts Double and Int values?

1

There are 1 answers

3
Yuval Itzchakov On BEST ANSWER

We can generalize the method a bit for any unary type constructor and avoid the type repetition (you can add a constraint for F[_] <: Seq[_] if you'd like):

def testFunc[F[_], A : Numeric](x: F[A]): F[A] = x

And then type inference works for us:

val resFirst = testFunc(Seq(1.0,2.0,3.0))
val resSecond = testFunc(List(1,2))