Kotlin and discriminated unions (sum types)

ehnmark picture ehnmark · Feb 24, 2015 · Viewed 15.7k times · Source

Does Kotlin have anything like discriminated unions (sum types)? What would be the idiomatic Kotlin translation of this (F#):

type OrderMessage =
    | New of Id: int * Quantity: int
    | Cancel of Id: int

let handleMessage msg = 
    match msg with
        | New(id, qty) -> handleNew id qty
        | Cancel(id) -> handleCxl id

Answer

Adeynack picture Adeynack · Aug 19, 2016

Kotlin's sealed class approach to that problem is extremely similar to the Scala sealed class and sealed trait.

Example (taken from the linked Kotlin article):

sealed class Expr {
    class Const(val number: Double) : Expr()
    class Sum(val e1: Expr, val e2: Expr) : Expr()
    object NotANumber : Expr()
}