scalasequencescala-option

How to optimize this method in Scala?


Suppose I've got class A with method foo:

class A(x: Int) { def foo(): Option[Int] = if (x > 0) Some(x) else None }

Now I am writing function bar like this:

def bar(as: List[A]): Option[(A,  Int)] = for {
  a <- as.view.find(_.foo.nonEmpty)
  foo <- a.foo
} yield (a, foo)

The code above works fine but what it invokes the foo method twice for the found A instance. How to re-write bar to invoke method foo only once for the found A instance ?


Solution

  •  as.iterator.flatMap { a => a.foo.map { a -> _ } }.find(_ => true)