Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

scala - Type inference with existential type

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The correct way to do this is to use a type variable to give a name to T:

qux map { case x: SomeTrait[t] => x.foo(bar(x)) }

This way the compiler knows bar(x): t and so it's an acceptable argument to x.foo.

Or, alternately, you can combine foo and bar into one method (remember that methods can be local, so you can just define it where you need it):

def fooOfBar[T](x: SomeTrait[T]) = x.foo(bar(x))
qux map { fooOfBar(_) }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...