为什么在 Scala 2.8 中 Iterator 有一个 contains 方法但 Iterable 没有? [英] Why does Iterator have a contains method but Iterable does not, in Scala 2.8?

查看:20
本文介绍了为什么在 Scala 2.8 中 Iterator 有一个 contains 方法但 Iterable 没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 Iterables 上调用包含":-)

I would like to call 'contains' on my Iterables :-)

推荐答案

Iterable之所以没有contains方法是因为它的定义方式可以直接方差的后果.基本上,有两种类型签名对它有意义:

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

但这不会比第一个签名提供任何改进,使用 Any.

but that wouldn't offer any improvement over the first signature, using Any.

因此,您会看到 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.

这篇关于为什么在 Scala 2.8 中 Iterator 有一个 contains 方法但 Iterable 没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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