Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 482
adam77 Avatar asked May 27 '10 23:05

adam77


People also ask

What is true about iterators in Scala?

An iterator is not a collection, but rather a way to access the elements of a collection one by one. The two basic operations on an iterator it are next and hasNext. A call to it. next() will return the next element of the iterator and advance the state of the iterator.

What is iterable in Scala?

Iterable: A base trait for iterable collections. This is a base trait for all Scala collections that define an iterator method to step through one-by-one the collection's elements. [...] This trait implements Iterable's foreach method by stepping through all elements using iterator.

Is Scala iterator lazy?

Unlike operations directly on a concrete collection like List , operations on Iterator are lazy. A lazy operation does not immediately compute all of its results.


2 Answers

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.

like image 114
Daniel C. Sobral Avatar answered Sep 18 '22 13:09

Daniel C. Sobral


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))
like image 21
mkneissl Avatar answered Sep 20 '22 13:09

mkneissl