Skip to main content

Functions, Closures and Monads

· 2 min read
Sanjeev Sarda
High Performance Developer

What's the difference between a function, a closure and a monad? It's not a joke, it's a TLDR note.

Functions

Functions

A function is a reusable piece of code that takes in parameters and returns a value - it also usually has an explicit name. They only consume what's passed in. A pure function is one which doesn't mutate state and produces deterministic output.

public int add(int a, int b) {
return a + b;
}

Closures

An anonymous function which can access or "captures" variables from it's surrounding environment or scope. In Java we also have lambdas which are like closures, but can only capture variables from enclosing scope that are final or effectively final. In Rust, closures can capture variables by reference, mutable reference, or by value.

int x = 10;
Function<Integer, Integer> addX = (y) -> x + y;

Monads

A monad is more of a concept or a pattern that allows for chained computation with context. The context allows us to handle things like errors, optional values and async computation.

Optional.of(10)
.flatMap(x -> Optional.of(x + 1));