Optionals and Monads



Monad is a key concept of Functional Programming. A Monad is a design pattern which helps to represent a missing value. It allows to wrap a potential null value, allows to put transformation around it and pull actual value if present. By definition, a monad is a set of following parameters.

  • A parametrized Type − M<T>

  • A unit Function − T −> M<T>

  • A bind operation − M<T> bind T −> M<U> = M<U>

Key Operations

  • Left Identity − If a function is bind on a monad of a particular value then its result will be same as if function is applied to the value.

  • Right Identity − If a monad return method is same as monad on original value.

  • Associativity − Functions can be applied in any order on a monad.

Optional Class

Java 8 introduced Optional class which is a monad. It provides operational equivalent to a monad. For example return is a operation which takes a value and return the monad. Optional.of() takes a parameters and returns the Optional Object. On similar basis , bind is operation which binds a function to a monad to produce a monad. Optional.flatMap() is the method which performs an operation on Optional and return the result as Optional.

  • A parametrized Type − Optional<T>

  • A unit Function − Optional.of()

  • A bind operation − Optional.flatMap()

Example − Left Identity

Following example shows how Optional class obeys Left Identity rule.

import java.util.Optional;
import java.util.function.Function;

public class FunctionTester {
   public static void main(String[] args) {
      Function<Integer, Optional<Integer>> addOneToX 
         = x −> Optional.of(x + 1);
      System.out.println(Optional.of(5).flatMap(addOneToX)
         .equals(addOneToX.apply(5)));
   } 
}

Output

true

Example − Right Identity

Following example shows how Optional class obeys Right Identity rule.

import java.util.Optional;

public class FunctionTester {
   public static void main(String[] args) {
      System.out.println(Optional.of(5).flatMap(Optional::of)
         .equals(Optional.of(5)));
   } 
}

Output

true

Example - Associativity

Following example shows how Optional class obeys Associativity rule.

import java.util.Optional;
import java.util.function.Function;

public class FunctionTester {
   public static void main(String[] args) {
      Function<Integer, Optional<Integer>> addOneToX 
         = x −> Optional.of(x + 1);
      Function<Integer, Optional<Integer>> addTwoToX 
         = x −> Optional.of(x + 2);
      Function<Integer, Optional<Integer>> addThreeToX 
         = x −> addOneToX.apply(x).flatMap(addTwoToX);
      Optional.of(5).flatMap(addOneToX).flatMap(addTwoToX)
         .equals(Optional.of(5).flatMap(addThreeToX));
   } 
}

Output

true
Advertisements