问题描述
和
[A <: B]
和
[+B]
在 Scala 中?
推荐答案
Q[A <: B]
表示 class Q
可以带任何 class A
是 B
的子类.
Q[A <: B]
means that class Q
can take any class A
that is a subclass of B
.
Q[+B]
表示 Q
可以取任何类,但如果 A
是子类B
的子类,则 Q[A]
被认为是 Q[B]
的子类.
Q[+B]
means that Q
can take any class, but if A
is a subclass of B
, then Q[A]
is considered to be a subclass of Q[B]
.
Q[+A <: B]
表示Q
类只能取B
的子类,并传播子类关系.
Q[+A <: B]
means that class Q
can only take subclasses of B
as well as propagating the subclass relationship.
当你想做一些通用的事情时,第一个很有用,但你需要依赖 B
中的特定方法集.例如,如果您有一个带有 toFile
方法的 Output
类,您可以在任何可以传递到 Q
的类中使用该方法.
The first is useful when you want to do something generic, but you need to rely upon a certain set of methods in B
. For example, if you have an Output
class with a toFile
method, you could use that method in any class that could be passed into Q
.
当您想要创建与原始类行为相同的集合时,第二个很有用.如果你使用 B
并创建一个子类 A
,那么你可以在任何需要 B
的地方传递 A
.但是如果你取一个B
的集合,Q[B]
,你是否总是可以传入Q[A]
代替?一般来说,没有;在某些情况下,这是错误的做法.但是你可以说这是正确的做法,使用 +B
(covariance; Q
covaries--follows with--B
'子类的继承关系).
The second is useful when you want to make collections that behave the same way as the original classes. If you take B
and you make a subclass A
, then you can pass A
in anywhere where B
is expected. But if you take a collection of B
, Q[B]
, is it true that you can always pass in Q[A]
instead? In general, no; there are cases when this would be the wrong thing to do. But you can say that this is the right thing to do by using +B
(covariance; Q
covaries--follows along with--B
's subclasses' inheritance relationship).
这篇关于Scala 中的 A<:B 和 +B 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!