Why does Iterator have a contains method but Iterable does not, in Scala 2.8?

血红的双手。 提交于 2019-11-27 06:38:49

问题


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


回答1:


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

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

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

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.




回答2:


I don't know why contains is not defined on Iterable or TraversableOnce, but you could easily define it yourself:

class TraversableWithContains[A](underlying: TraversableOnce[A]) {
  def contains(v: Any): Boolean =
    underlying.exists(_ == v)
}
implicit def addContains[A](i: Iterable[A]) = new TraversableWithContains(i)

and use it as if it were defined on Iterable:

val iterable: Iterable[Int] = 1 to 4
assert(iterable.contains(3))
assert(!iterable.contains(5))


来源:https://stackoverflow.com/questions/2925765/why-does-iterator-have-a-contains-method-but-iterable-does-not-in-scala-2-8

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