I have several classes like these:
class Value[T]
class Container[T](v: Value[T], x: T)
Now I want to transform a sequence of (Value[T], T)
s into a sequence of Container[T]
s where T
for each element of the sequence can be different. Such type can be expressed with existentials:
def mapContainer(s: Seq[(Value[T], T) forSome {type T}]): Seq[Container[T] forSome {type T}]
However, it appears I can't write the body of this function. My naive attempt has failed:
def mapContainer(s: Seq[(Value[T], T) forSome {type T}]) =
s.map(t => new Container(t._1, t._2))
The error looks like this:
[error] found : Value[T]
[error] required: Value[Any]
[error] Note: T <: Any, but class Var is invariant in type T.
I can't make Value
covariant and anyway this wouldn't be the proper solution, I believe.
That being said, I'm also fine with the result type Seq[Container[_]]
, but I couldn't find a way to get it as well.
Is it possible to express this without resorting to asInstanceOf
and such?
Solution:
Rewrite
s.map(t => new Container(t._1, t._2))
to
s.map { case (v, x) => new Container(v, x) }
Unfortunately I do not have an explanation of why the former does not work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.