The monad type

interface Monad<out A> {
    fun <B> flatMap(f: (A) -> Monad<B>): Monad<B>
}

sealed class Option<out A> : Monad {
    data class Some<A>(val value: A) : Option<A>()
    class None : Option()

    override infix fun <B> flatMap(f: (A) -> Monad<B>): Option<B> =
            when (this) {
                is Some -> f(value) as Option
                is None -> None()
            }
}

 

Advertisements