CodeBlanks Logo Icon CodeBlanks

Monad

Learn monad patterns like Result and Either.

Monads: Result and Either

A monad wraps a value in a context and provides chainable operations. In Kotlin Result<T> wraps a success or failure. Either<L, R> (from the Arrow library) represents two possible types.

Example: Result.of { 10 / 2 }.map { it * 3 }. On failure the chain short-circuits. Result provides type-safe error handling instead of throwing. This pattern treats errors as values; it reduces side effects.

Result.success and failure

Result.success(v) creates a success, Result.failure(e) a failure. getOrNull() returns the value or null; getOrElse provides a default.

Example: val r: Result<Int> = Result.success(5); val v = r.getOrNull(). On failure, getOrNull returns null. fold handles both cases with separate lambdas. This pattern manages errors explicitly.

Practice Safe division with Result

Define a function safeDiv(a: Int, b: Int): Result<Int> that returns Result.failure(ArithmeticException()) if b is 0, otherwise Result.success(a / b). In main print the result of safeDiv(10, 2).getOrNull() with println.

Starter code

Main.kt
// safeDiv function: returns failure if b is 0, success otherwise
// in main get safeDiv(10, 2) via getOrNull and print

Sample solution

Main.kt
fun safeDiv(a: Int, b: Int): Result<Int> {
    return if (b == 0) Result.failure(ArithmeticException())
    else Result.success(a / b)
}

fun main() {
    println(safeDiv(10, 2).getOrNull())
}

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the Result.map call

Question
val r = Result.success(10).____ { it * 3 }
Answer
val r = Result.success(10).map { it * 3 }

Explanation: Result.map transforms the success value.

2 Match the monad parts

Term Meaning
Result<T> Context
map { } Transform
success(v) Success case
getOrNull() Value or null

3 What does Result.failure(e) represent?

  • A successful value
  • A null value
  • An empty list
  • A failure case Correct answer

Explanation: Result.failure wraps an error.

All lessons in Advanced