如何从投影类型推断出正确的类型参数?

bet*_*ess 11 polymorphism scala type-inference type-projection

我有一些麻烦让Scala从类型投影中推断出正确的类型.

考虑以下:

trait Foo {
  type X
}

trait Bar extends Foo {
  type X = String
}

def baz[F <: Foo](x: F#X): Unit = ???
Run Code Online (Sandbox Code Playgroud)

然后以下编译好:

val x: Foo#X = ???    
baz(x)
Run Code Online (Sandbox Code Playgroud)

但以下内容无法编译:

val x: Bar#X = ???    
baz(x)
Run Code Online (Sandbox Code Playgroud)

斯卡拉认为"基础String类型"的x,但已失去了信息xBar#X.如果我注释类型,它工作正常:

baz[Bar](x)
Run Code Online (Sandbox Code Playgroud)

有没有办法让Scala推断出正确的类型参数baz
如果没有,那么一般的答案是什么让它变得不可能?

bet*_*ess 2

该程序通过在上下文中添加此隐式转换来进行编译:

implicit def f(x: Bar#X): Foo#X = x
Run Code Online (Sandbox Code Playgroud)

由于这种隐式转换对于 any 是正确的F <: Foo,我想知道为什么编译器不自行执行此操作。