Kevin, in hindsight, I disagree with you.
Scala's for/yield returns a collection, in this case a collection of size
0-1 which is an Option, which lets you do this:
val barOpt : Option[Bar] = for (f <- fooOpt) yield getBarFomFoo f;
instead of:
val barOpt : Option[Bar] = fooOpt map getBarFromFoo
and this:
val barOpt : Option[Bar] = for (f <- fooOpt; b <- tryToGetBarFromFoo(f))
yield b;
instead of:
val barOpt : Option[Bar] = fooOpt flatMap tryToGetBarFromFoo
Internally, the for/yield route compiles and optimizes down to the function
passing route. In the trivial case, I can't see a strong reason to prefer
one over the other. In more complex cases, I suspect one route may be more
logical than the other.
I could boil my original exmample to:
Function Passing, verbose Scala:
val optA: Option[A] = tryToProduceA
val optB: Option[B] = optA flatMap tryToGetBFromA
optB foreach doSomethingWithNonNullB
Function Passing, compact Scala:
tryToProduceA flatMap tryToGetBFromA foreach doSomethingWithNonNullB
For/Yield verbose Scala:
val optA: Option[A] = tryToProduceA
val optB: Option[B] = for (a <- optA; b <- tryToGetBFromA(a)) yield b;
for (b <- optB) doSomethingWithNonNullB(b)
For/Yield compact Scala:
for (a <- tryToProduceA(); b <- tryToGetBFromA(a))
doSomethingWithNonNullB(b)
You said that function passing route was non-idiomatic Scala, while
for/yield was. On the #scala irc channel, everyone told me the opposite,
that higher order functions were the Scala way, and that the for/yield
route was unecessary syntactic sugar. To me, it looks like an issue of
taste in the trivial case, and in different specific cases, I'd imagine one
form is more natural and logical than the other.
I'm using Option today in my Java code when I can't use Scala. My team
mates like the Functional Java Option better than Google Guava Option. Java
8 lambdas will make Option much more usable, but you're right that the
Scala for/yield construct that returns a collection is also important and
isn't even on the Java road map.
On Friday, July 27, 2012 3:04:39 AM UTC-5, KWright wrote:
>
> That's terribly non-idiomatic though, the Scala version would more
> normally be written as:
>
> for {
> a <- methodThatMayProduceA
> b <- tryToGetBFrom(a)
> } {
> doSomethingWith(b)
> }
>
>
> I also stripped out the semicolons and empty parameter list (which is
> typically only used to denote a method with side effects)
>
>
--
You received this message because you are subscribed to the Google Groups "Java
Posse" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/javaposse/-/fat8krfsRWwJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/javaposse?hl=en.