views:

247

answers:

1

Option is implicitly convertible to an Iterable - but why does it not just just implement Iterable directly:

def iterator = new Iterator[A] {
  var end = !isDefined
  def next() = {
    val n = if (end) throw new NoSuchElementException() else get
    end = true
    n
  }

  def hasNext = !end
}

EDIT: In fact it's even weider than that because in 2.8 Option does declare an iterator method:

def iterator: Iterator[A] = 
  if (isEmpty) Iterator.empty else Iterator.single(this.get)
+5  A: 

I'm thinking that there were too many non-nonsensical methods that would be required. For example, what would you expect the return value to be for:

Some(1) ++ Some(2)

This currently compiles and evaluates to List(1,2) via implicits in 2.8, but seems odd.

Maybe that is why the doc comments in 2.7 say:

Only potentially unbounded collections should directly sub-class Iterable

Edit: As shown in @MattR's comment below, me leaving out the doc-comment recommendation to sub-type Collection is potentially misleading. And considering it morphs this question into "Why does Option not extend the Collection trait?"

Mitch Blevins
The documentation says, "If a collection has a known size, it should also sub-type Collection. Only potentially unbounded collections should directly sub-class Iterable".
Matt R
@Matt - if you post that as an answer, it will get accepted!
oxbow_lakes
@oxbow: I'm not sure it should! The question is then only slightly different: why should Option not subtype Collection, which is a "Variant of Iterable used to describe collections with a finite number of elements"?
Matt R