That's a bit open-ended, are you thinking of a particular construct that
you think would be challenging to convert?

As another trivial example, something like this:

final A a = getA();
if (a != null) {
    final B b = getBFrom(a);
    if (b != null) {
  doSomethingWithB(b);
  } else {
        doSomethingIfBWasAbsent();
    }
} else {
    doSomethingIfAWasAbsent();
}


Or with the tertiary operator:

final A a = getA();
(a == null) ? doSomethingIfAWasAbsent() : {
    final B b = getBFrom(a);
    (b == null) ? doSomethingIfBWasAbsent() : {
  doSomethingWithB(b);
}
};


Could be written in Scala as:

val a = getA
val b = a flatMap {getBFrom}
a getOrElse {doSomethingIfAWasAbsent()}
b getOrElse {doSomethingIfBWasAbsent()}
b forEach {doSomethingWithB}





On 27 July 2012 04:16, Cédric Beust ♔ <[email protected]> wrote:

> Yes but that's the most trivial case. For example, experiment with your
> Option code when the original code has else's.
>
> --
> Cédric
>
>
>
>
> On Thu, Jul 26, 2012 at 5:30 PM, 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.

Reply via email to