concept IO type in category kotlin
appears as: IO type, The IO type

This is an excerpt from Manning's book The Joy of Kotlin.
Listing 12.11 Changes in the stack-safe version of
IOsealed class IO<out A> { #1 operator fun invoke(): A = invoke(this) #2 operator fun invoke(io: IO<@UnsafeVariance A>): A { #3 tailrec fun invokeHelper(io: IO<A>): A = when (io) { #4 ... } return invokeHelper(io) } fun <B> map(f: (A) -> B): IO<B> = flatMap { Return(f(it)) } #5 fun <B> flatMap(f: (A) -> IO<B>): IO<B> = Continue(this, f) as IO<B> #6 class IORef<A>(private var value: A) { fun set(a: A): IO<A> { value = a return unit(a) } fun get(): IO<A> = unit(value) fun modify(f: (A) -> A): IO<A> = get().flatMap({ a -> set(f(a)) }) } internal class Return<out A>(val value: A): IO<A>() internal class Suspend<out A>(val resume: () -> A): IO<A>() internal class Continue<A, out B>(val sub: IO<A>, val f: (A) -> IO<B>): IO<A>() companion object { val empty: IO<Unit> = IO.Suspend { Unit } #7 internal fun <A> unit(a: A): IO<A> = IO.Suspend { a } #8 // rest of the class omitted } } #1 The IO type is now a sealed class. #2 The invoke function now calls the helper function invoke(this). #3 The invoke(this) function, in turn, calls the invokeHelper function that’s made tail-recursive. #4 The invokeHelper function is shown in listing 12.12. #5 The map function is now defined in terms of applying flatMap to the composition of f and the Return constructor. #6 The flatMap function returns a Continue that’s cast into an IO<B>. #7 The empty IO is now a Suspend. #8 The unit function returns a Suspend.