Sealed Class And Algebraic data type

Hi, I am from functional programming language background( Standard ML), but work in a java company now. I really miss the Algrebaric data type.

data List a = Nil | Cons a (List a)

It create a base type ‘List’, and two subtype ‘Nil’ and ‘Cons’.

I think sealed class is a kind of Algebraic Data type. Below is what I try in Kotlin

sealed class List<T>

class Nil<T> : List<T>()

data class Cons<T>(val a : T, val b : List<T>) : List<T>()

Does the Nil type must have generic in definition? Is there any better way?

I think you need to mark your generic parameters as out, so variance would be correct (List<Int> could be assigned to variable of type List<Number>, for example). Now about Nil: just use Nothing type, it’s compatible for every type. So your example would be:

fun main(args: Array<String>) {
    val l1: List<Int> = Cons(1, Cons(2, Cons(3, Nil())))
    val l2: List<Number> = l1

tailrec fun <T> printList(l: List<T>) {
    when (l) {
        is Cons -> {
            print("${l.a} ")
        is Nil -> Unit

sealed class List<out T>

class Nil : List<Nothing>()

data class Cons<out T>(val a : T, val b : List<T>) : List<T>()

That works. Thank you!

You may want to make Nil an object rather than a class. No need to create multiple instances of it. :slight_smile:

1 Like