Scala 无法推断逆变Nothing类型参数
考虑以下代码段:Scala 无法推断逆变Nothing类型参数,scala,scala-compiler,Scala,Scala Compiler,考虑以下代码段: trait X[-T] object Y extends X[Nothing] def a[T](x: X[T]): X[T] = x a(Y) 上述(2.12.3)的编制未能满足以下条件: type mismatch; found : Y.type required: X[T] a(Y) ^ 如果出现以下情况,则可以进行编译: 所使用的类型与未使用的类型不同(例如,对象Y扩展X[String]) 方法a在其返回类型中不使用t(例如defa[t](x:
trait X[-T]
object Y extends X[Nothing]
def a[T](x: X[T]): X[T] = x
a(Y)
上述(2.12.3)的编制未能满足以下条件:
type mismatch;
found : Y.type
required: X[T]
a(Y)
^
如果出现以下情况,则可以进行编译:
- 所使用的类型与未使用的类型不同(例如,
)对象Y扩展X[String]
- 方法
在其返回类型中不使用a
(例如t
)defa[t](x:x[t]):Unit={}
- 明确给出了
的类型参数(即a
)a[无](Y)
是协变的,而不是逆变的(如果不变也会失败)T
trait X[-T]
object Y extends X[Nothing]
def a[T, U <: T](x: X[T]): X[U] = x
a(Y)
trait X[-T]
对象Y扩展X[无]
defa[T,U我将尝试逐行解释代码
第1行:trait X[-T]
->trait X在类型T中是逆变的。因此,您可以用其子类型替换任何类型X[T]的变量。对于逆变类型,如果B是A的子类型,则Z[A]是Z[B]的子类型
第2行:对象Y扩展了X[Nothing]
->对象Y的类型为X[Nothing]。请注意,Nothing是所有其他类型的子类型
第3行:defa[T](x:x[T]):x[T]=x
->定义一个接受x[T]类型参数的表达式。因为特质x在类型T中是逆变的,所以也可以传递x[T]的子类型,即x[N],使T是N的子类型
第4行:a(Y)
->使用类型为X[Nothing]的参数调用表达式“a”。由于编译器不知道参数“a”的类型,因此无法确定X[Nothing]是否为X[T]的子类型。有多种方法可解决此问题
Solution 1: `a[Nothing]` -> explicitly defining the type
Solution 2: `tait X[+T]` -> make X covariant in type T. In this case Z[A] is subtype of Z[B] if A is subtype of B. This will work because Nothing is subtype of any other type
感谢您的回答,但是为什么使用String
而不是Nothing
可以使示例编译?或者为什么这项工作可以解决问题?