Wednesday, 10. September
9:12:29 PM
myself
DA Development Teletext

What is a monad?

A monad is a pretty cool design pattern in functional programming: it’s a way to wrap a value, and then chain operations on that wrapped value in a consistent, predictable way.
Think of it as:

“A box that holds a value, plus rules for how to apply functions to what’s inside.”

The Kotlin Arrow library gives us some essential utilities using monads:

#1 The Option monad

Represents a value that might be missing.

import arrow.core.*

val maybeName: Option<String> = Some("Alice")
// val maybeName: Option<String> = None
val result: Option<Int> =
  maybeName.flatMap { name ->
    if (name.length > 3) Some(name.length) else None
  }
  
println(result) // Some(5)

#2 The Either monad

Represents either a success (Right) or a failure (Left).

import arrow.core.*

fun parseInt(s: String): Either<String, Int> =
  s.toIntOrNull()?.right() ?: "Not a number".left()

val result = parseInt("42")
  .flatMap { n -> if (n > 0) (n * 2).right() else "Must be positive".left() }

println(result) // Right(84)

#3 Syntactical sugar

Arrow lets you write monadic code as if it were imperative:

import arrow.core.computations.option

val result = option {
  val a = Some(10).bind()
  val b = Some(5).bind()
  a + b
}

println(result) // Some(15)

Arrow offers a whole range of cool features! Take a closer look at the website or documentation. It's worth it!

© 2025 David Angenendt

Legal notice