Union

@Serializable
sealed class Union

Union types for representing TypeScript union types in Kotlin.

TypeScript union types like string | number | boolean are represented using Union classes (U2, U3) in Kotlin.

Usage Examples

Binary Union (U2)

// TypeScript: string | number
val value: Union.U2<String, Number> = Union.U2.ofA("hello")
// or
val value2: Union.U2<String, Number> = Union.U2.ofB(42)

// Check which type it is
if (value.isA()) {
println(value.valueOfA()) // "hello"
}

Ternary Union (U3)

// TypeScript: string | number | boolean
val value: Union.U3<String, Number, Boolean> = Union.U3.ofA("hello")
// or
val value2: Union.U3<String, Number, Boolean> = Union.U3.ofB(42)
val value3: Union.U3<String, Number, Boolean> = Union.U3.ofC(true)

Serialization

Union types are automatically serialized/deserialized when used in AST nodes. The serializer will try each type in order until one succeeds.

See also

for binary unions

for ternary unions

Inheritors

Types

Link copied to clipboard
@Serializable(with = Union.U2.U2Serializer::class)
data class U2<A, B>(val a: A? = null, val b: B? = null) : Union

Binary union type: A | B

Link copied to clipboard
@Serializable(with = Union.U3.U3Serializer::class)
data class U3<A, B, C>(val a: A? = null, val b: B? = null, val c: C? = null) : Union

Ternary union type: A | B | C