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开发者_如何学JAVA declare an iterator
method:
def iterator: Iterator[A] =
if (isEmpty) Iterator.empty else Iterator.single(this.get)
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?"
精彩评论