concept Empty in category kotlin

appears as: Empty, n Empty
The Joy of Kotlin

This is an excerpt from Manning's book The Joy of Kotlin.

Note that there’s another possibility that consists in creating an Empty<A> abstract class for representing empty lists and then creating a Nil<Nothing> singleton object. This lets you define abstract functions in the List parent class with specific implementation in Cons or Empty. Here’s how the concat function could be defined:

You might think you should go the other way and convert an Option into a Result. This would work (although, in our example, you should call the new toResult function on both Option instances returned by Map.get and Toon.getMail), but it would be tedious. Because you’ll usually have to convert Option to Result, a much better way would be to cast this conversion into the Result class. All you have to do is to create a new subclass corresponding to the None case. The Some case doesn’t need conversion, apart from changing its name for Success. The next listing shows the new Result class with the new subclass called Empty.

Listing 7.6 The new Result class handling errors and optional data
sealed class Result<out A>: Serializable {

    abstract fun <B> map(f: (A) -> B): Result<B>

    abstract fun <B> flatMap(f: (A) ->  Result<B>): Result<B>

    fun getOrElse(defaultValue: @UnsafeVariance A): A = when (this) {
        is Result.Success -> this.value
        else -> defaultValue    #1  
    }

    fun getOrElse(defaultValue: () -> @UnsafeVariance A): A = when (this) {
        is Result.Success -> this.value
        else -> defaultValue()   #1  
    }

    fun orElse(defaultValue: () -> Result<@UnsafeVariance A>): Result<A> =
        when (this) {
            is Success -> this
            else -> try {   #1  
                defaultValue()
            } catch (e: RuntimeException) {
                Result.failure<A>(e)
            } catch (e: Exception) {
                Result.failure<A>(RuntimeException(e))
            }
        }

    internal object Empty: Result<Nothing>() {    #4  

        override fun <B> map(f: (Nothing) -> B): Result<B> = Empty

        override fun <B> flatMap(f: (Nothing) -> Result<B>): Result<B> =
                                                                      Empty

        override fun toString(): String = "Empty"
    }

    internal
    class Failure<out A>(private val exception: RuntimeException):
                                                            Result<A>() {

        override fun <B> map(f: (A) -> B): Result<B> = Failure(exception)

        override fun <B> flatMap(f: (A) -> Result<B>): Result<B> =
                                                        Failure(exception)

        override fun toString(): String = "Failure(${exception.message})"
    }

    internal class Success<out A>(internal val value: A) : Result<A>() {

        override fun <B> map(f: (A) -> B): Result<B> = try {
            Success(f(value))
        } catch (e: RuntimeException) {
            Failure(e)
        } catch (e: Exception) {
            Failure(RuntimeException(e))
        }

        override fun <B> flatMap(f: (A) -> Result<B>): Result<B> = try {
            f(value)
        } catch (e: RuntimeException) {
            Failure(e)
        } catch (e: Exception) {
            Failure(RuntimeException(e))
        }

        override fun toString(): String = "Success($value)"
    }

    companion object {

        operator fun <A> invoke(a: A? = null): Result<A> = when (a) {
            null -> Failure(NullPointerException())
            else -> Success(a)
        }

        operator fun <A> invoke(): Result<A> = Empty    #5  

        fun <A> failure(message: String): Result<A> =
                        Failure(IllegalStateException(message))

        fun <A> failure(exception: RuntimeException): Result<A> =
                        Failure(exception)

        fun <A> failure(exception: Exception): Result<A> =
                        Failure(IllegalStateException(exception))
    }
}

#1   The getOrElse and orElse functions have been modified to handle the Empty case.
#4   Like the None instance in Option, Result contains a singleton instance of Empty, parameterized with Nothing.
#5   Like Option, the invoke function that takes no parameter returns the Empty singleton.