Estimate project
← All posts

Kotlin and Functional Programming

Kotlin advertises itself as multi-paradigm, and FP is one of the paradigms it claims. How much of that claim survives in practice? Is idiomatic functional Kotlin possible without external libraries? Let's check.

11 min read
Functional ProgrammingKotlinProgramming Languages

Functional programming makes me think of three things: immutability, monads, and side effects. Immutability deserves its good name - it really does make code easier to reason about and concurrency safer. Monads? Powerful, yet daunting. And side effects? Any useful program has them. It reads files, calls APIs, and writes to databases. The real question is not how to get rid of them, but how to keep them in check.

Kotlin advertises itself as multi-paradigm, and FP is one of the paradigms it claims. How much of that claim survives in practice? Is idiomatic functional Kotlin possible without external libraries?

Who is this blog post for?

If immutability and higher-order functions are already familiar to you, read on. I won’t be covering map and filter. If you’re curious how functional Kotlin truly is, or you’ve simply had enough of the “it depends” answer, this post is for you. If you’re already well versed in effect systems, most of this will be familiar, though the casual vs. pure FP framing may still come in handy.

What makes a language “functional”?

Before evaluating Kotlin, we have to settle on a yardstick. Functional programming isn’t a yes-or-no checkbox. It’s closer to a spectrum, with “I use map sometimes” at one extreme and “everything is an IO monad” at the other.

A handy distinction helps here: there’s casual FP, and there’s pure FP. Casual FP means treating functions as first-class citizens (passing them as arguments and returning them from other functions), embracing immutability, using higher-order functions, modeling the domain with algebraic data types, and generally favoring expressions over statements. Pure FP goes a step further: side effects are tracked by the type system, referential transparency is enforced, and the whole program is essentially a composition of pure functions.

What’s the interesting takeaway? Most of the practical gains come from stepping into casual FP territory. Moving from imperative code to casual FP is a larger leap than moving from casual to pure. You get cleaner code, fewer bugs, and better testability. Switching to pure FP brings mathematical guarantees, but for most business applications the ROI is questionable.

Casual FP: Where Kotlin delivers

We’ll start with what Kotlin brings to casual functional programming. This includes the basics most teams need: immutability, pure functions, higher-order functions, and algebraic data types.

Immutability

Kotlin separates mutable collections from immutable ones and promotes immutability through the way the language is designed.

val users = listOf(
    User("Alice", 28),
    User("Bob", 35)
)

listOf() produces an immutable list. Once it has been created, elements can’t be added, removed, or changed.

val updatedUsers = users + User("Charlie", 42)

Adding an element yields a new list and leaves the original one intact.

data class User(val name: String, val age: Int)

A data class with val properties is immutable by default. Together with the copy() method, this makes modeling an immutable domain feel natural.

Kotlin doesn’t force immutability on you (var and mutableListOf() are still available), but it gives you the tools and steers you the right way. Keep in mind that val makes only the reference immutable, not the underlying data structure. The standard library uses immutable collections by default.

Pure functions

Pure functions can be written in any language, Kotlin included.

fun processOrder(order: Order): Order {
    return order.copy(
        total = calculateDiscount(order.total, order.discountPercent)
    )
}

Thanks to the copy() method on data classes, the “return a modified copy rather than mutate” pattern comes naturally. In contrast to Haskell, Kotlin doesn’t enforce purity at compile time. In other words, nothing in the compiler prevents you from introducing side effects into a function.

First-class and higher-order functions

In Kotlin, functions are first-class citizens. They can be passed as parameters, returned from other functions, and kept in variables.

val square: (Int) -> Int = { it * it }
fun applyTwice(f: (Int) -> Int, x: Int): Int {
    return f(f(x))
}

val result = applyTwice(square, 3)  // 81

Here a higher-order function takes another function as a parameter. This pattern makes powerful abstractions possible, such as map, filter, and custom control flow. It is a cornerstone of functional programming, and Kotlin supports it gracefully through lambda syntax and function types.

Standard library FP operations

The Kotlin standard library offers extensive support for functional operations on collections:

data class Product(val name: String, val price: Double, val inStock: Boolean)

val products = listOf(
    Product("Laptop", 999.0, true),
    Product("Mouse", 25.0, false),
    Product("Keyboard", 75.0, true)
)

val affordableInStock = products
    .filter { it.inStock }           // (1)
    .filter { it.price < 100 }       // (2)
    .map { it.name.uppercase() }     // (3)
    .sorted()                        // (4)

// Result: ["KEYBOARD"]
  1. Retain only items that are in stock
  2. Filter on price
  3. Map to uppercase names
  4. Sort in alphabetical order

The collection API includes map, filter, flatMap, fold, reduce, groupBy, partition, and plenty more. For everyday functional transformations, you won’t feel constrained.

Algebraic Data Types (ADTs)

Kotlin supports ADTs very well via sealed classes/interfaces and data classes.

sealed interface PaymentResult {
    data class Success(val transactionId: String) : PaymentResult
    data class Declined(val reason: String) : PaymentResult
    data object NetworkError : PaymentResult
}

This is a sum type (sealed interface), where the result takes the form of one of several variants. For variants that carry no data, use data object.

fun handlePayment(result: PaymentResult): String = when (result) {
    is PaymentResult.Success -> "Payment successful: ${result.transactionId}"
    is PaymentResult.Declined -> "Payment declined: ${result.reason}"
    is PaymentResult.NetworkError -> "Network error, please retry"
}

An exhaustive when expression - the compiler makes sure every case is covered. Add a new variant, and every when expression that doesn’t handle it will stop compiling.

This is almost the same as sum types in languages such as Scala or Rust. Exhaustiveness checking by the compiler is especially useful: when a new variant is added, the compiler points out each when expression that has to be updated.

Pattern matching

For sealed types, Kotlin’s when expression offers exhaustive pattern matching:

sealed interface ApiResponse<out T> {
    data class Success<T>(val data: T) : ApiResponse<T>
    data class Error(val code: Int, val message: String) : ApiResponse<Nothing>
    data object Loading : ApiResponse<Nothing>
}

fun <T> renderResponse(response: ApiResponse<T>): String = when (response) {
    is ApiResponse.Success -> "Data: ${response.data}"
    is ApiResponse.Error -> "Error ${response.code}: ${response.message}"
    ApiResponse.Loading -> "Loading..."
}  // Compiler checks exhaustiveness

For most use cases this is very capable: you gain type safety and exhaustiveness checking, so missing cases are caught at compile time.

Tail Call Optimization

Kotlin does support tail call optimization, but only through the explicit tailrec annotation and under strict constraints.

tailrec fun factorial(n: Long, acc: Long = 1): Long =
    if (n <= 1) acc
    else factorial(n - 1, n * acc)

You must add the tailrec annotation. The recursive call has to sit in tail position, i.e. it must be the final operation of the function.

factorial(10000)  // Works without stack overflow

With tailrec, the compiler turns the recursion into a loop, so deep recursion doesn’t overflow the stack.

Limitations:

  • Applies only to direct recursion (mutual recursion isn’t supported)
  • The function has to be private, final, or local
  • The recursive call has to be the final operation

Contrast this with Scala, where TCO applies automatically to calls in tail position. The explicit annotation is in fact a hidden feature: if you write non-tail recursion by mistake, the compiler tells you right away rather than letting it fail at runtime.

Type-Safe Nullability

Instead of the Option/Maybe types typical of FP languages, Kotlin relies on nullable types (T?).

fun findUser(id: String): User? = userRepository.find(id)

A nullable return type - the ? suffix expresses absence explicitly in the type system.

val username = findUser("123")?.name?.uppercase()

Chains of the safe call operator (?.) - when any step yields null, the whole chain short-circuits to null.

val username = findUser("123")?.name?.uppercase() ?: "Unknown"

The Elvis operator (?:) supplies a default value whenever the left-hand side is null.

This approach works and is type-safe, yet it isn’t equivalent to Option<T>. Option gives you methods such as map, flatMap, fold, which turn it into a proper monad:

// Kotlin nullable — imperative style
val user: User? = findUser("123")
val department = user?.department?.name ?: "Unknown"

// Option style (not in Kotlin stdlib)
val user: Option<User> = findUser("123")
val department = user
    .flatMap { it.department }
    .map { it.name }
    .getOrElse { "Unknown" }

In most practical situations Kotlin’s nullable types suffice, and for simple cases they are arguably easier to read. However, once you want to chain several fallible operations in a functional way, nullable types get clumsy. You end up writing nested ?.let { } blocks.

Pure FP: What’s missing?

Let’s spell out what Kotlin lacks for pure functional programming; you should be aware of these gaps before going all-in on a purely functional approach.

Limited pattern matching

when expressions cope well with basic pattern matching, but Kotlin has no guards and no destructuring in match clauses:

// Not possible in Kotlin
when (result) {
    is Success(data) if data.isEmpty() -> ...  // Guards not supported
    is Error(404, _) -> ...                     // Can't destructure in when
}

Workaround: Put nested conditions inside the branches:

when (result) {
    is ApiResponse.Success -> {
        if (result.data.isEmpty()) "Empty data"
        else "Data: ${result.data}"
    }
    is ApiResponse.Error -> {
        if (result.code == 404) "Not found"
        else "Error: ${result.message}"
    }
    ApiResponse.Loading -> "Loading..."
}

It’s wordier, but it does the job. Missing guards are an annoyance rather than a blocker - the same logic can always be expressed, only with deeper nesting.

No built-in function composition

Kotlin ships no built-in operators for composing functions. Composition has to be done by hand:

val addOne: (Int) -> Int = { it + 1 }
val double: (Int) -> Int = { it * 2 }

// Manual composition (works but reads right-to-left)
val addThenDouble = { x: Int -> double(addOne(x)) }

// Better: write your own extension
infix fun <A, B, C> ((A) -> B).andThen(g: (B) -> C): (A) -> C = { g(this(it)) }

val composed = addOne andThen double  // (1)
composed(5)  // 12

Composing with a custom extension function

Languages such as Scala offer compose and andThen out of the box. In Kotlin, you either write those extensions on your own (5 lines of code) or pull in a library. The workaround is simple, but it’s surprising that the standard library doesn’t include it.

No native either/result type for errors

Kotlin does have a Result<T> type, but it was built specifically to wrap exceptions and can’t represent arbitrary error types:

fun divide(a: Int, b: Int): Result<Int> =
    if (b == 0) Result.failure(ArithmeticException("Division by zero"))
    else Result.success(a / b)

divide(10, 0).getOrElse { -1 }

The problem: Domain errors can’t be modeled elegantly:

sealed interface ValidationError {
    data object EmptyEmail : ValidationError
    data object InvalidFormat : ValidationError
    data class TooLong(val maxLength: Int) : ValidationError
}

// What we want:
fun validateEmail(email: String): Either<ValidationError, Email>

// What Kotlin gives us:
fun validateEmail(email: String): Result<Email>  // Can only hold Exception

Lacking Either<E, A>, you have no choice but to:

  1. Throw exceptions (which isn’t functional)
  2. Return nullable types (which discards error information)
  3. Write your own Either type (which means boilerplate)
  4. Rely on a library such as Arrow

No effect system

Kotlin has no built-in effect system. In functional languages, effect types such as IO<A>, Option<A>, or Either<E, A> wrap computations and express their properties through the type - Option stands for presence/absence, IO for an operation that may have side effects, and Either for failure or success.

// Kotlin: no effect system
fun loadUser(id: String): User = userRepository.find(id)

The (String) -> User type says nothing about what the function actually does. Does it do I/O? Might it fail? Does it cause side effects?

Languages with effect systems make the type explicit:

-- Haskell: IO effect
loadUser :: String -> IO User
// Scala with Cats Effect
def loadUser(id: String): IO[User]

IO stands for an operation that may have side effects. Rather than the result itself, the function returns a description of the work to perform. The Kotlin suspend modifier comes closest to an effect marker, but it merely marks suspension points for coroutines, not effects in general:

No higher-kinded types

Kotlin doesn’t support higher-kinded types (HKTs), which allow abstracting over type constructors such as List, Option, or Either. Without HKTs, generic code that works with any F[_] type constructor is impossible, which restricts how far you can go in building generic functional abstractions.

Scala lets you write functions that operate on any container type:

// Generic function that works with any F[_]
def transform[F[_]: Functor, A, B](fa: F[A], f: A => B): F[B] =
  fa.map(f)

// Works with List, Option, Either, etc.
transform(List(1, 2, 3), _ * 2)        // List(2, 4, 6)
transform(Some(5), _ * 2)              // Some(10)
transform(Right(5), _ * 2)             // Right(10)

The F[ _ ] syntax reads as “F is a type constructor taking a single type parameter.” It allows you to write code once and have it work with any container-like type.

Kotlin offers no way to express this abstraction. You would have to write separate implementations for List, nullable types, Result, and so forth.
. At the moment, there are no plans to add HKTs to Kotlin.

No type classes

Interfaces in Kotlin aren’t type classes (a mechanism also known as ad-hoc polymorphism). You can neither add implementations retroactively nor define laws that instances have to obey:

// Kotlin interface: must be declared when defining the class
interface Showable {
    fun show(): String
}

// Can't make String showable without wrapping it
data class DisplayString(val value: String) : Showable {
    override fun show() = value
}

Scala and Haskell let you define a type class instance for any existing type without touching it:

trait Showable[A]:
extension (a: A) def show: String

val stringShowable = new Showable[String]:
extension (value: String) def show: String = value

Extension functions in Kotlin offer some of the same advantages; they are resolved statically (at compile time, according to the declared type).

Conclusion

As a casual FP language, Kotlin holds up well. It equips you for immutability, higher-order functions, algebraic data types, and exhaustive pattern matching. Without any external dependencies you can write clean, functional code: data transformation pipelines, immutable domain models, and pure business logic. For the majority of teams and projects, that is sufficient.

Kotlin comes up short in pure FP territory. There’s no typed error handling apart from exceptions, no effect tracking, no type classes, and no compiler-enforced referential transparency. To get those guarantees, you need Arrow.

My recommendation: don’t fight the language. Reach for nullable types when they keep things simpler, throw exceptions when the alternative would be worse, and lean on sealed classes for domain modeling. For basics such as function composition, write your own 5-line extensions. But once you catch yourself building a custom Either type, it’s time to bring in Arrow.

Part 2 will look at how Arrow closes these gaps and when adding that dependency to your project pays off.