Skip to content
Junior–Middle277 views

How to implement and use the monad pattern in your code?

Practice

Asked at

AI answer

A monad pattern is an abstraction that allows wrapping values in a context and applying operations to them sequentially, preserving the context structure. In Java, an example of a monad can be the Optional class.

To implement a monad, you need:

  • Create a wrapper class with a type parameter.
  • Implement a flatMap (or bind) method that takes a function from the value to a monad and returns a new monad.
  • Implement a unit (or of) method that wraps a value into a monad.

Simple "Box" monad example:

public class Box<T> {
    private final T value;

    public Box(T value) {
        this.value = value;
    }

    public <R> Box<R> flatMap(Function<T, Box<R>> f) {
        return f.apply(value);
    }

    public static <T> Box<T> of(T value) {
        return new Box<>(value);
    }

    public T get() {
        return value;
    }
}

// Usage:
Box<Integer> box = Box.of(5);
Box<Integer> result = box.flatMap(x -> Box.of(x * 2));
System.out.println(result.get()); // 10

Thus, a monad allows applying operations sequentially without leaving the context (wrapper). In real projects, ready-made monads like Optional, Stream, or functional programming libraries are often used.