为什么Iterator在Scala 2.8中有一个contains方法但是Iterable没有? [英] Why does Iterator have a contains method but Iterable does not, in Scala 2.8?
问题描述
我想在我的Iterables上调用'contains': - )
I would like to call 'contains' on my Iterables :-)
推荐答案
原因 Iterable
没有包含
方法,因为它的定义方式会对方差产生直接影响。基本上,有两种类型的签名对它有意义:
The reason Iterable
does not have a contains
method is because the way it is defined can have direct consequences on variance. Basically, there are two type signatures that make sense for it:
def contains(v: Any): Boolean
def contains(v: A): Boolean
第二个定义增加了类型安全性。但是, A
(它是集合的类型参数)出现在反变量位置,这会强制集合不变。 可以定义如下:
The second definition has increased type safety. However, A
, which is the type parameter of collection, appears in a contra-variant position, which forces the collection to be invariant. It could be defined like this:
def contains[B >: A](v: B): Boolean
但是使用<$ c,这不会比第一个签名提供任何改进$ c>任何。
因此,你会看到 immutable.Seq
是共变体并使用第一个签名,而 immutable.Set
是不变的并且使用第二个签名。
As a consequence of this, you'll see that immutable.Seq
is co-variant and uses the first signature, while immutable.Set
is invariant and uses the second signature.
这篇关于为什么Iterator在Scala 2.8中有一个contains方法但是Iterable没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!