views:

246

answers:

1

I have an Iterator[Option[T]] and I want to get an Iterator[T] for those Options where T isDefined. There must be a better way than this:

it filter { _ isDefined} map { _ get }

I would have thought that it was possible in one construct... Anybody any ideas?

+10  A: 

In the case where it is an Iterable

val it:Iterable[Option[T]] = ...
it.flatMap( x => x )                //returns an Iterable[T]

In the case where it is an Iterator

val it:Iterator[Option[T]] = ...
it.flatMap( x => x elements )       //returns an Iterator[T]
it.flatMap( _ elements)             //equivalent
DRMacIver
Knowing who you are (from the scala-user mailing list), you are right I'm sure (don't have access to my Scala dev envt at the moment :-). Can you explain a bit how this works. I promise I'm not an idiot but I have no idea how I would be supposed to get this from the scaladoc
oxbow_lakes
Would it not be "it flatMap { _ elements }" ? (I've read the scaladoc again!)
oxbow_lakes
It would be great to see more Scala gurus on StackOverflow. The scala-user mailing list is filling up my inbox with arcane arguments over break/continue :-)
oxbow_lakes
As I see it, what you have to do is just flatten your iterable, but since Iterable doesn't have a flatten method, you use flatMap and the (x => x) simply means no actual mapping is required, you only get the effect of flattening. Still, I'd like to see a good explanation w/the scaladoc description.
Germán
Apologies. I've just noticed that the topic and body don't ask the same question. I answered the body rather than the topic. it.flatMap(x => x) will turn an Iterable[Option[T]] into an Iterable[T]. it.flatMap(_.elements) will turn an Iterator[Option[T]] into an Iterator[Option[T]].
DRMacIver
What do you mean that the topic and body don't ask the same question? Yes they do...
oxbow_lakes
No. The topic asks about an Iterator, the body asks about an Iterable.
DRMacIver
Many apologies - I meant Iterator, not Iterable!
oxbow_lakes