Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best scala idiom for find & return

This is something I encounter frequently, but I don't know the elegant way of doing. I have a collection of Foo objects. Foo has a method bar() that may return null or a Bar object. I want to scan the collection, calling each object's bar() method and stop on the first one returning an actual reference and return that reference from the scan.

Obviously:

foos.find(_.bar != null).bar

does the trick, but calls #bar twice.

like image 541
IttayD Avatar asked Mar 18 '10 13:03

IttayD


1 Answers

Working on the Stream[T] returned by Seq.projection is a nice trick

foos.projection map (_.bar) find (_.size > 0)

This will map the values needed to execute find.

In Scala 2.8 it's:

foos.view map (_.bar) find (_.size > 0)
like image 99
Thomas Jung Avatar answered Oct 13 '22 13:10

Thomas Jung