如何从投影类型推断正确的类型参数? [英] How to infer the right type parameter from a projection type?
问题描述
使用Scala从类型投影中推断正确的类型时,我会遇到一些麻烦.
I have some troubles having Scala to infer the right type from a type projection.
请考虑以下内容:
trait Foo {
type X
}
trait Bar extends Foo {
type X = String
}
def baz[F <: Foo](x: F#X): Unit = ???
然后以下代码可以正常编译:
Then the following compiles fine:
val x: Foo#X = ???
baz(x)
但是以下内容无法编译:
But the following won't compile:
val x: Bar#X = ???
baz(x)
Scala看到x
的底层类型字符串",但是丢失了x
是Bar#X
的信息.如果我注释类型,它会很好地工作:
Scala sees the "underlying type String" for x
, but has lost the information that x
is a Bar#X
. It works fine if I annotate the type:
baz[Bar](x)
是否有一种方法可以使Scala推断baz
的正确类型参数?
如果没有,什么使它不可能呢?
Is there a way to make Scala infer the right type parameter for baz
?
If not, what is the general answer that makes it impossible?
推荐答案
程序通过在上下文中添加此隐式转换来进行编译:
The program compiles by adding this implicit conversion in the context:
implicit def f(x: Bar#X): Foo#X = x
由于这种隐式转换对任何F <: Foo
都是正确的,所以我想知道为什么编译器本身不会这样做.
As this implicit conversion is correct for any F <: Foo
, I wonder why the compiler does not do that by itself.
这篇关于如何从投影类型推断正确的类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!