当`class B extends A` 和`L <: A` 时,为什么`List[B]` 不是`Seq[L]` 的子类型? [英] Why `List[B]` is not a subtype of `Seq[L]` when `class B extends A` and `L &lt;: A`?

查看:55
本文介绍了当`class B extends A` 和`L <: A` 时,为什么`List[B]` 不是`Seq[L]` 的子类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有:

class A
class B extends A

正确的写法:

val foo: Seq[A] = List[B](new B)

出错时我会错过什么?

def bar[L <: A](): Seq[L] = List[B](new B)

错误:

[error]  found   : List[B]
[error]  required: Seq[L]
[error]     def t[L <: A](): Seq[L] = List[B](new B)

推荐答案

你的 bar 方法的签名本质上是在说,告诉我 A 的一些子类型和我'会给你一系列那种类型的东西.A 可能有很多子类型,而 B 不是其子类型(即,在这种情况下,所有这些子类型),因此实现像 这样的方法List[B](new B) 不起作用.

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.

这篇关于当`class B extends A` 和`L <: A` 时,为什么`List[B]` 不是`Seq[L]` 的子类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆