Arun Pandian M

Arun Pandian M

Android Dev | Full-Stack & AI Learner

Written by: Arun Pandian M•Published on: Nov 23, 2026

Sum Types in Kotlin: An Introduction

Sum Types in Kotlin: An Introduction

In functional programming, sum types are a powerful way to model alternatives. They allow us to represent a value that can be one of several distinct options, each potentially carrying its own data. Kotlin provides a practical way to implement sum types using sealed interface and sealed class, which enable us to define finite sets of alternatives and safely inspect them with pattern matching.

Core Concepts of Sum Types

A sum type, often written as A | B, represents a value that can be either A or B. This is in contrast to a product type, such as A × B, which represents a value that contains both A and B. Sum types are particularly useful for modeling situations where a value can be in one of several known states, such as a user profile that is either loading, loaded, or in an error state.

https://storage.googleapis.com/lambdabricks-cd393.firebasestorage.app/fp_sum_type_img.svg?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=firebase-adminsdk-fbsvc%40lambdabricks-cd393.iam.gserviceaccount.com%2F20261123%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20261123T200842Z&X-Goog-Expires=3600&X-Goog-SignedHeaders=host&X-Goog-Signature=59c12c81dc6e2a27fac7081d85bbd53759a86c893eae35d0368ada2e37481473cabf2a80e30c18649aa27d80225c32a8ccf917f476ccbe893e2427d91ca6765aef593dc2cd58c646ecb22541dc7286317f77081c79f80c72f1537fc8d88aa7ef314fff19af9fa23c04b3d3a8814cfb8c959a27148b93d26cc64df5c54110669717a62755f1b3649b8ead4269619d7fbe2b6df006aa3e3f065c25b61b1674819f622b83adc25ffc10bd8f403036771826c810645a6230781c6361073f326624fd331a4794d5545fb96a4b328aac06d08335c770e657271cb8ea08f19c855915d257c8706997c27a7123aeb6fe9fdfcbbabc06be76f0ebc7a842f76460b8a89877

Kotlin's sealed interface and sealed class are used to define sum types. A sealed type restricts its direct subclasses to a known set, allowing the compiler to reason about the complete hierarchy for exhaustiveness checking. This makes it possible for the compiler to enforce exhaustiveness when we use pattern matching with when.

Pattern Matching with when

In Kotlin, we use the when expression to inspect and handle different alternatives of a sum type. The when expression can check for all possible subtypes of a sealed type, ensuring that we handle every case. This is known as exhaustiveness checking, and it helps prevent missing cases in our logic.

For example, consider a PaymentResult type that can be either a Success or a Failed:

sealed interface PaymentResult {
    data class Success(val transactionId: String) : PaymentResult
    data class Failed(val message: String) : PaymentResult
}

We can use when to handle both cases:

fun handlePaymentResult(result: PaymentResult) {
    when (result) {
        is PaymentResult.Success -> {
            // Handle success case
        }
        is PaymentResult.Failed -> {
            // Handle failure case
        }
    }
}

This ensures that we are handling all possible cases of the PaymentResult type.

Enums as a Special Case of Sum Types

When the alternatives of a sum type do not carry any additional data, we can use enum class instead of a sealed type. For example, an enum class can represent a set of colors:

enum class Color {
    RED, GREEN, BLUE
}

This is a simple sum type where each alternative is a distinct value with no associated data.

Nullable Types and Value Absence

From a type-theory perspective, Kotlin’s nullable type T? can be viewed as representing either a value of type T or null, making it useful for modeling optional values. This is useful for modeling optional values, such as a user's nickname:

val nickname: String?

However, when the alternatives have different meanings or require additional data, a sealed type is usually clearer and more expressive.

The Either Type

The Either type is a common example of a sum type used in functional programming. It represents one of two alternatives, and it is often used to model outcomes such as success or failure. In Kotlin, we can define an Either type as follows:

sealed interface Either<out A, out B> {
    data class Left<out A>(val value: A) : Either<A, Nothing>
    data class Right<out B>(val value: B) : Either<Nothing, B>
}

This can be used to model operations that may succeed or fail:

fun divide(a: Int, b: Int): Either<String, Int> {
    return if (b == 0) Either.Left("Division by zero") else Either.Right(a / b)
}

Recursive Sum Types

Sum types can also be used to model recursive data structures. A classic example is a linked list, which can be either empty (Nil) or a cons cell containing a value and a tail (Cons):

sealed interface MyList<out A> {
    data object Nil : MyList<Nothing>
    data class Cons<out A>(val head: A, val tail: MyList<A>) : MyList<A>
}

This recursive definition allows us to build and inspect lists in a functional way.

Immutability and Sum Types

Sum types work particularly well with immutable values: once an alternative is created, its state can remain stable, making the model predictable and easier to reason about. Once a value is created, it cannot change, which makes it predictable and safe to use. For example, once we create a Success value, it remains a Success:

val result: PaymentResult = PaymentResult.Success("TXN-1001")

If we need a failure value, we create a new value:

val failed: PaymentResult = PaymentResult.Failed("Network error")

This ensures that the original value does not change, and the behavior of the system is predictable.

Domain Modeling with Sum Types

Sum types are especially useful in domain modeling, where we need to represent a finite set of known states. For example, an OrderState can be one of several known states:

sealed interface OrderState {
    data object Pending : OrderState
    data class Confirmed(val orderId: String) : OrderState
    data class Cancelled(val reason: String) : OrderState
    data class Delivered(val trackingId: String) : OrderState
}

This makes the domain explicit and safe to work with, as the valid alternatives are part of the type.

Conclusion

Sum types are a powerful tool for modeling alternatives in Kotlin. They allow us to represent a value that can be one of several distinct options, each potentially carrying its own data. Kotlin's sealed interface and sealed class provide a practical way to implement sum types, and the when expression allows us to safely inspect and handle each alternative. By using sum types, we can write more expressive, safe, and predictable code.

#AlgebraicDataTypes#SealedInterfaces#ComputerScience#FP#PatternMatching#TypeSystems#SoftwareEngineering#Kotlin#CategoryTheory#SumTypes#FunctionalProgramming#Maybe#Either#Programming#SealedClasses#ProductTypes
LAMBDA BRICKS