Skip to content

Instantly share code, notes, and snippets.

@janojanahan
janojanahan / MonadicNullSafety.kt
Last active March 23, 2023 02:46
Kotlin Nullable can behave like a monad
/**
* A Gist proving that Kotlin's nullable type can be made into a monad without wrapping into another
* object and satisfy the Monadic laws
*
* Kotlin has comprehensive null safety built into the language enforced at compile time, using its
* nullable type.
*
* Its language structure makes dealing with nullable values simple and succinct. Unlike other language
* monadic constructs such as Option (scala), Optional(Java8+) and Maybe(Haskell), it is enforced at
* compile time and is compatible with existing non monad aware API (for example,
import java.util.Optional;
import java.util.function.Function;
/**
* A Gist prooving that Java 8's Optional type satisfies the Monadic laws
*
* Based on the idea originally by Marc Siegel <marc.siegel@timgroup.com>, at:
* https://gist.github.com/ms-tg/7420496
*
* However, updated to the final/released version of Java 8 (Marcs version was based on pre-release