Back to list

Arrow-style Either Type

Lv.51021@mukitaro0 playsJan 2, 2026

Arrow functional programming pattern with Either type for error handling.

preview.kotlin
Kotlin
1import arrow.core.*
2import arrow.core.raise.*
3
4sealed class UserError {
5 data class NotFound(val id: Int) : UserError()
6 data class ValidationError(val message: String) : UserError()
7 data object DatabaseError : UserError()
8}
9
10data class User(val id: Int, val name: String, val email: String)
11
12fun findUser(id: Int): Either<UserError, User> =
13 if (id > 0) {
14 User(id, "User$id", "user$id@example.com").right()
15 } else {
16 UserError.NotFound(id).left()
17 }
18
19fun validateEmail(email: String): Either<UserError, String> =
20 if (email.contains("@")) email.right()
21 else UserError.ValidationError("Invalid email").left()
22
23fun processUser(id: Int): Either<UserError, String> = either {
24 val user = findUser(id).bind()
25 val validEmail = validateEmail(user.email).bind()
26 "Processed: ${user.name} <$validEmail>"
27}
28
29fun main() {
30 when (val result = processUser(1)) {
31 is Either.Left -> println("Error: ${result.value}")
32 is Either.Right -> println(result.value)
33 }
34}

Custom problems are not included in rankings