Search code examples
javaprogramming-languages

What's the reason for having conditional expressions and not loop expressions?


I'm using Java 6.

Do you think there's a reason why there are conditional expressions

String plan = ( isEconomyGood() ? "find a job" : "stay with mom" ) ;

and not loop expressions

weeklyPlan.add( schedule.hasNext() => schedule.next() );

which adds elements from schedule into weeklyPlan while hasNext().

Or do some languages have this feature or something similar?


Solution

  • I think it's because conditional expressions are much easier to implement without having to worry about pesky details. For example, looking at your code, are you saying that weeklyPlan.add will be called multiple times? In that case, the scope of your => operator just jumped outside of the parentheses that contain it.

    C# has features in LINQ that can perform similar actions to what you're describing. It implements these using closures and extension methods:

    schedule.AsParallel().ForAll(s => weeklyPlan.add(s));
    

    But these are much more tricky language constructs than Java started out with and the .NET runtime has been able to change much more rapidly than the Java platform has, largely for political reasons. Java 7 was supposed to feature closures, but they got pushed back to the "next version."