I have a generic trait SomeTrait
defined as so:
trait SomeTrait[T] {
def foo(t: T): String
}
And methods bar
and qux
as so:
def bar[T](t: SomeTrait[T]): T
def qux: List[SomeTrait[_]]
I do not have control over the above. I am trying to operate on the list returned by qux
, like so
qux map { x => x.foo(bar(x))}
However, the compiler complains that the types don't match up. As far as I know this should be fine.
I have tried adding a generic method (signature [T](SomeTrait[T])String
), and calling that to do the work, but the compiler still complains. I can cast my way around it like this:
qux map { x =>
val casted = x.asInstanceOf[SomeTrait[T forSome { type T }]] // !!!
casted.foo(bar(casted))
}
But this is even more perplexing, as x
already has the type SomeTrait[_]
and SomeTrait[T forSome { type T }]
means the same thing. The only difference that I'm aware of is that the former is a shorthand for the latter that makes the compiler create its own synthetic names. I'm hoping there's a better way to do this. I have seen this question however I don't think it applies.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…