Best scala idiom for search and return

This is what I often encounter, but I do not know how to do it. I have a collection of Foo objects. Foo has a bar () method that can return null or a Bar object. I want to scan the collection by calling each object bar () method and stopping at the first one that returns the actual link and returns that link from the scan.

Obviously:

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

does the trick, but calls #bar twice.

+6
scala scala-collections
source share
2 answers

You can do this with any Iterable using an iterator (which evaluates lazily - it's called elements in 2.7). Try it:

 case class Foo(i: Int) { def bar = { println("Calling bar from Foo("+i+")") (if ((i%4)==0) "bar says "+i else null) } } val foos = List(Foo(1),Foo(2),Foo(3),Foo(4),Foo(5),Foo(6)) foos.iterator.map(_.bar).find(_!=null) 
+7
source share

Work on thread [T] returned by Seq.projection is a nice trick

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

This will display the values ​​needed to complete the search.

In Scala 2.8, this is:

 foos.view map (_.bar) find (_.size > 0) 
+8
source share

All Articles