-4

I am moving from scala to java8 and looking for examples on how to assign value to a variable by computing block of code with multiple if's.

Given Scala code for reference.

Below works in Scala

object HelloWorld {
    def main(args: Array[String]) = {
        val x = if(condition1) {
                    ....
                    ....
                    ....
                    if(condition2){
                     ....
                     ....
                      "something1"
                    }else
                      "something2"
                  }
                 else
                   "mydefault"
        println(x)
    }

Is there any style of coding other than below inline function example.

String x = (args.length > 0)? args[0]:"default";

But, how to write the same in Java8 programming style ?

Jai
  • 343
  • 1
  • 9

2 Answers2

1

Scala is an expression-oriented language, so the if block there has a return value. Java does not have this. The equivalent is either to:

final String x = (args.length > 0) ? args[0] : "default";

or make a function that has the logic hidden inside if it's more complex than a simple check.

final String x = getXFromArgs(args);

I use final here because that's the effect of the scala val, in contrast to var

Daenyth
  • 35,856
  • 13
  • 85
  • 124
1

Actually this is in Java 8 (as well as Java 7 etc.):

public class HelloWorld {
    public static void main(String[] args) {
        final String x = (args.length > 0) ? args[0] : "mydefault";
        System.out.println(x);
    }
}

final String x = (args.length > 0)? args[0]:"default"; is pretty functional since it's expression-oriented, side-effects free and immutable.


If you insist on "functional Java 8" you can do also

public class HelloWorld {
    public static void main(String[] args) {
        final String x = Stream.of(args).findFirst().orElse("mydefault");
        final Consumer<String> cons = System.out::println;
        cons.accept(x);
    }
}

but I guess this would be overkill.

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • 1
    @Dmyto Thanks for the "functional java 8" code.I got the style and i understood its overkill for this simple case. – Jai Sep 27 '17 at 14:08
  • @Jai You're welcome. The "most functional" would be to [emulate](https://stackoverflow.com/questions/876948/higher-kinded-generics-in-java) [higher-kinded](https://medium.com/@johnmcclean/simulating-higher-kinded-types-in-java-b52a18b72c74) generics and encapsulate side effects (like printing to console) in [monad](https://stackoverflow.com/questions/44965/what-is-a-monad/) [IO](https://stackoverflow.com/questions/19687470/scala-io-monad-whats-the-point). But this would be an overkill squared (at least squared). – Dmytro Mitin Sep 27 '17 at 14:31