Question

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)
Was it helpful?

Solution

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?"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top