问题
Having:
class A
class B extends A
It is correct to write:
val foo: Seq[A] = List[B](new B)
What do I miss while having an error in?
def bar[L <: A](): Seq[L] = List[B](new B)
Error:
[error] found : List[B]
[error] required: Seq[L]
[error] def t[L <: A](): Seq[L] = List[B](new B)
回答1:
The signature of your bar
method is essentially saying, tell me some subtype of A
and I'll give you a sequence of things of that type. There are potentially a lot of subtypes of A
that B
is not a subtype of (i.e., all of them in this case), so implementing such a method as List[B](new B)
isn't going to work.
More concretely: suppose your code compiled, and then I wrote the following:
class NotB extends A {
def doSomething(): Unit
}
bar[NotB]().head.doSomething()
This would also have to compile, but it wouldn't make any sense.
来源:https://stackoverflow.com/questions/18216878/why-listb-is-not-a-subtype-of-seql-when-class-b-extends-a-and-l-a