Why `List[B]` is not a subtype of `Seq[L]` when `class B extends A` and `L <: A`?

谁说胖子不能爱 提交于 2019-12-12 16:34:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!