Type inference with existential type

I have a common symptom SomeTraitdefined as such:

trait SomeTrait[T] {
  def foo(t: T): String
}

And methods barand quxas such:

def bar[T](t: SomeTrait[T]): T
def qux: List[SomeTrait[_]]

I have no control over the above. I am trying to work in a list returned quxby e.g.

qux map { x => x.foo(bar(x))}

However, the compiler complains that the types do not match. As far as I know, this should be good.

I tried adding a generic method (signature [T](SomeTrait[T])String) and calling it to do the job, but the compiler still complains. I can get around this as follows:

qux map { x =>
  val casted = x.asInstanceOf[SomeTrait[T forSome { type T }]] // !!!
  casted.foo(bar(casted))
}

, x SomeTrait[_], SomeTrait[T forSome { type T }] . , , , , . . , , .

+2
1

- , T:

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

, bar(x): t x.foo.

, , foo bar (, , , ):

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

Source: https://habr.com/ru/post/1695919/


All Articles