[英]Bug in Scala's type system?
The following scala code seems to be valid: 以下scala代码似乎有效:
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: 我希望编译器在类型A上执行类型推断,但是在我尝试以下操作之后:
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]] )
Let's see what this means in plain English. 让我们用简单的英语看看这意味着什么。
class A[X]
means: let A be a class that takes one type parameter. 意思是:让A成为一个带有一个类型参数的类。
class C[M[X] <: A[X]]
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. 意味着:让C成为一个带有一个类型参数的类,该类应该是一个带有一个类型参数的类AND,参数化,是一个用相同类型参数化的类A的子类。
When you write 当你写作
new C[A]
you're saying: create an instance of C with A as parameter. 你说的是:用A作为参数创建一个C实例。 Does A conform to the criteria above?
A符合上述标准吗? Yes, it's a class that takes one type parameter, and parameterized it is a subclass of itself parameterized.
是的,它是一个接受一个类型参数的类,并且参数化它是自身参数化的子类。
However, when you write 但是,当你写作
new C[A[Int]]
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. 您尝试给C,A [Int]的类型参数不符合条件:A [Int]不接受任何类型参数,编译器会告诉您。 (And it is not a subclass of A[X] either.)
(它也不是A [X]的子类。)
Try this syntax. 试试这个语法。
class C[M <: A[_]]
This means that C is a class that takes one type parameter, which should be a subclass of A and takes one type parameter. 这意味着C是一个带有一个类型参数的类,它应该是A的子类并且需要一个类型参数。
You didn't declare X
as a type parameter for C
. 您没有将
X
声明为C
的类型参数。 Try the following: 请尝试以下方法:
class C[X, M[X] <: A[X]]
这一切都在这里解释,关注“常见陷阱”部分,因为它非常TLTR。
You don't wan't your class to take ONE type parameter, you wan't it to take two! 你不要让你的班级拿一个类型的参数,你不要拿两个! Two possible solutions:
两种可能的解决方
class A[X] {
type T = X
}
class C[M <: A[_]] {
//use M#T if you want the type T was parameterized with.
}
Or, you can do: 或者,您可以这样做:
class A[X]
class C[T, M[A] <: A[A]] {
//when you want the type, write M[T], not M.
}
HOWEVER, what you probably want is this: 但是,你可能想要的是:
class A[X]
class C[M <: A[_]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.