Reputation: 51165
I am trying to write a function that takes an Traversable of functions, and a Traversable of values, and returns a Traversable of functions applied to those values. I am getting a type mismatch error when I try to call the function on a list and a vector. Here is my code:
def applyFunctions[A](x: Traversable[A => A], y: Traversable[A]): Traversable[A] = {
for (ys <- y;
xs <- x
) yield (xs(ys))
}
And then I try and call this function using this:
transform(List({(x: Double) => x + x}, {(x: Double) => x * 2}), Vector(1,2,3))
And I get the following error:
error: type mismatch;
found : List[Double => Double]
required: Traversable[AnyVal => AnyVal]
I thought that List was a subclass of Traversable, so I could able to use Traversable in the function definition. Any help would be appreciated.
Upvotes: 1
Views: 160
Reputation: 1231
Type parameter A
is deduced from all arguments of function. Your first argument has type List[Double => Double]
however second argument is of type Vector[Int]
. Common ancestor of Double
(A
from first argument) and Int
(A
from second argument) is AnyVal
and that's why it is final value of A
.
To fix your issue, change Vector(1,2,3)
to Vector(1.0,2.0,3.0)
.
Upvotes: 0
Reputation: 215037
The Vector is interpreted as Vector[Int], you can declare it as Vector[Double] since it should have the same type as the type A in the functions, which is Double:
applyFunctions(List({(x: Double) => x + x}, {(x: Double) => x * 2}), Vector[Double](1,2,3))
// res9: Traversable[Double] = Vector(2.0, 2.0, 4.0, 4.0, 6.0, 6.0)
Upvotes: 1