Is it possible to write a generalised orElse
method from Option
that takes a variable number of arguments? That is, instead of:
lazy val o1 = { println("foo"); None }
lazy val o2 = { println("bar"); Some("bar") }
lazy val o3 = { println("baz"); Some("baz") }
// ...
o1 orElse o2 orElse o3 // orElse ...
You could use:
orElse(o1, o2, o3) //, ...
I found the question a bit late :). One possibility is to wrap
=> A
into a helper class together with a helper function to simplify its creation:The extractor isn't required, it just allows easy matching on the helper. Then we can write
This is just a simplified solution, a more realistic one would be
with a more efficient implementation.
There already is a class similar to
Helper
in Scalaz, calledName
with implementationNeed
that ensures that the body is evaluated at most once. So with Scalaz, it could be implemented asAccording to the The Scala Language Specification (4.6 Function Declarations and Definitions) you cannot define varargs by-name parameters:
You could replace the lazy arg with function and an implicit type conversion: