简体   繁体   English

Nala的Scala类型参数推断失败

[英]Scala type parameter inference fails for Nothing

scala> class A[T]
defined class A

scala> class B[T](a: A[T])
defined class B

scala> val b = new B(new A[Int])
b: B[Int] = B@1ff8982d

Great! 大! I can create instances of B from instances of A . 我可以从A实例创建B的实例。 With one exception. 有一个例外。 For instances of A[Nothing] the type inference fails. 对于A[Nothing]的实例,类型推断失败。

scala> val b = new B(new A[Nothing])
<console>:9: error: type mismatch;
 found   : A[Nothing]
 required: A[T]
Note: Nothing <: T, but class A is invariant in type T.
You may wish to define T as +T instead. (SLS 4.5)
       val b = new B(new A[Nothing])

Specifying the type manually works. 手动指定类型有效。

scala> val b = new B[Nothing](new A[Nothing])
b: B[Nothing] = B@3aad5958

Should I file a bug for it, or is it an intentional trap to scare away programmers that lack sufficient resolve for Scala? 我应该为它提交一个错误,还是一个故意的陷阱来吓跑那些对Scala缺乏足够决心的程序员?

The answer is in the compilation feedback. 答案在于汇编反馈。 You need to declare A as being covariant in T, so that when you don't specify the type parameter during the construction of a new B, the compiler can infer that the A[Nothing] may be treated as type T (or treat the A[T] parameter as a T). 您需要将A声明为T中的协变,因此当您在构造新B期间未指定type参数时,编译器可以推断A [Nothing]可以被视为类型T(或处理A [T]参数为T)。 That's be basic idea behind covariance. 这是协方差背后的基本思想。

自2008 以来,这已被人们所熟知并被忽视为问题SI-1570 。假设没有人将Scala用于任何严肃的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM