简体   繁体   中英

Bug in Scala's type system?

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]] )

Let's see what this means in plain English.

class A[X]

means: let A be a class that takes one type parameter.

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.

When you write

new C[A]

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

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. (And it is not a subclass of A[X] either.)

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.

You didn't declare X as a type parameter for 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[_]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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