Scala 类型系统中的错误?
下面的scala代码似乎是有效的:
class A[X]
class C[M[X] <: A[X]]
class Main
new C[A]
我期望编译器对类型A执行类型推断,但是在我尝试以下操作之后:
new C[A[Int]]
我收到以下错误消息:
(fragment of Main.scala):11: error: this.A[Int] takes no type parameters, expected: one
println( new C[A[Int]] )
The following scala code seems to be valid:
class A[X]
class C[M[X] <: A[X]]
class Main
new C[A]
I expected the compiler to perform type inference on type A, but after I tried the following:
new C[A[Int]]
I got the following error message:
(fragment of Main.scala):11: error: this.A[Int] takes no type parameters, expected: one
println( new C[A[Int]] )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
让我们看看这用简单的英语意味着什么。
意思是:设 A 是一个带有一个类型参数的类。
意思是:设 C 是一个采用一个类型参数的类,它应该是一个采用一个类型参数的类,并且参数化后是具有相同类型参数化的类 A 的子类。
当您编写时
,您是在说:创建一个以 A 作为参数的 C 实例。 A 是否符合上述标准?是的,它是一个带有一个类型参数的类,并且参数化它是参数化本身的子类。
但是,当您编写
类型参数时,您尝试给 C A[Int] 提供的类型参数不符合标准:A[Int] 不采用任何类型参数,编译器会善意地告诉您这一点。 (它也不是 A[X] 的子类。)
Let's see what this means in plain English.
means: let A be a class that takes one type parameter.
means: let C be a class that takes one type parameter, which should be a class that takes one type parameter AND, parameterized, is a subclass of class A parameterized with the same type.
When you write
you're saying: create an instance of C with A as parameter. Does A conform to the criteria above? Yes, it's a class that takes one type parameter, and parameterized it is a subclass of itself parameterized.
However, when you write
the type parameter you're trying to give C, A[Int], does not conform to the criteria: A[Int] does not take any type parameters, which the compiler kindly tells you. (And it is not a subclass of A[X] either.)
试试这个语法。
这意味着 C 是一个带有一个类型参数的类,它应该是 A 的子类并且带有一个类型参数。
Try this syntax.
This means that C is a class that takes one type parameter, which should be a subclass of A and takes one type parameter.
您没有将
X
声明为C
的类型参数。请尝试以下操作:You didn't declare
X
as a type parameter forC
. Try the following:您不希望您的类采用一个类型参数,您不希望它采用两个!两种可能的解决方案:
或者,您可以这样做:
但是,您可能想要的是:
You don't wan't your class to take ONE type parameter, you wan't it to take two! Two possible solutions:
Or, you can do:
HOWEVER, what you probably want is this:
一切都在此处进行了解释,重点关注“常见陷阱”部分,因为它非常长。
It's all explained here, focus on the "Common Pitfalls" section because it is quite TLTR.