Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Option not extend the Iterable trait directly?

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)
like image 495
oxbow_lakes Avatar asked Apr 09 '10 11:04

oxbow_lakes


1 Answers

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

like image 117
Mitch Blevins Avatar answered Oct 16 '22 07:10

Mitch Blevins