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)
This style won't be possible in Java even after it gets lambdas. Though I
have high hopes that comprehensions will be proposed for the language some
point around Java 12 (a may even be added by the time we reach Java 15)
On 27 July 2012 01:30, clay <[email protected]> wrote:
> Here is a simple example that illustrates the benefit of Option beyond
> avoiding null exceptions:
>
> Here is a traditional piece of logic using traditional null if-checks.
> This is using Scala syntax but would be equivalent in Java.
>
> val variableAMayBeNull: A = methodThatMayProduceA();
> if (variableAMayBeNull != null) {
> val variableBMayBeNull: B = tryToGetBFromA(variableAMayBeNull);
>
> if (variableBMayBeNull != null) {
> doSomethingWithNonNullB(variableBMayBeNull);
> }
> }
>
> Same logic using Option. This is Scala syntax. Java can do this but not as
> nicely until it gets lambdas.
>
> val variableAMayBeNull: Option[A] = methodThatMayProduceA();
> val variableBMayBeNull: Option[B] =
> variableAMayBeNull.flatMap(tryToGetBFromA);
> variableBMayBeNull.foreach(doSomethingWithNonNullB);
>
> Both blocks are logically equivalent, but the Option route is much more
> concise, elegant, and maintainable. The if-logic is moved from the end
> application code to inside of the Option class. Since this type of logic is
> so common in application code, the code simplification benefits are quite
> large.
>
>
--
You received this message because you are subscribed to the Google Groups "Java
Posse" group.
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.