Chapter 7. Statements

When we think of a statement, we think of something like Integer x = 1; or val x = 1 where we are setting a variable. Technically, that line evaluates to nothing, but what if we had already defined a variable, and we were setting it later—something like x = 1? Some people already know that in C and Java, this statement actually returns 1, as shown in Example 7-1.

Example 7-1. A simple assignment statement
public class Test {

  public static void main(String[] args) {
    Integer x = 0;
    System.out.println("X is " + (x = 1).toString());
  }

}

Statements in functional programming introduce the idea that every line of code should have a return value. Imperative languages such as Java incorporate the concept of the ternary operator. This gives you an if/else structure that evaluates to a value. Example 7-2 shows a simple usage of the ternary operator.

Example 7-2. A simple ternary statement
public class Test {

  public static void main(String[] args) {
    Integer x = 1;
    System.out.println("X is: " + ((x > 0) ? "positive" : "negative"));
  }

}

But if we’re able to make more use of statements, we can actually reduce the number of variables we have. If we reduce the number of variables that we have, we reduce the ability to mutate them and thus increase our ability to perform concurrent processes and become more functional!

Taking the Plunge

Your boss is very happy with what you’ve been doing over at XXY. He’s actually impressed with functional programming and wants you to convert from ...

Get Becoming Functional now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.