Error using object to implement empty list

I am trying to rewrite the List interface as an exercise to learn functional programming in Kotlin, but I can’t understand why I get an error message when I try to get an object as an empty list that is not found in the Kotlin standard library. In my code, see below, I want to use NIL as a singleton empty list, using list () as a function to return it. However, this creates a type mismatch error for a function of type "Required list. Found NIL"

interface List<A> {
    val empty: Boolean
    val head: A
    val tail: List<A>

    fun cons(a: A): List<A> = Cons(a, this)
}

object NIL : List<Nothing> {
    override val empty: Boolean = true
    override val head: Nothing
        get() = throw IllegalStateException("head called on empty list")

    override val tail: List<Nothing>
        get() = throw IllegalStateException("tail called on empty list")
}

private class Cons<A>(override val head: A,
                      override val tail: List<A>) : List<A> {
    override val empty: Boolean = false
}

fun <A> list(): List<A> = NIL // Type mismatch. Required: List<A>. Found: NIL

fun <A> list(vararg a: A): List<A> {
    var n = list<A>()
    for (e in a.reversed()) {
        n = Cons(e, n)
    }
    return n
}

, EmptyList Collections.kt. - , , , ?

, , - , , java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Void.

assertEquals("a", list<String>().cons("a").head)

, NIL NIL : List<Any?>, NIL as List<A> .

+4
2

List<Nothing> List<A> as, :

fun <A> list(): List<A> = NIL as List<A>;

IF , @Suppress, :

@Suppress("UNCHECKED_CAST")
fun <A> list(): List<A> = NIL as List<A>;

, , funtion, :

fun <A> list(): List<A> = object : List<A> {
    override val empty: Boolean = true
    override val head: A
        get() = throw IllegalStateException("head called on empty list")

    override val tail: List<A>
        get() = throw IllegalStateException("tail called on empty list")
};
0

<out A> <A>.

, IntelliJ Idea , .

+2

Source: https://habr.com/ru/post/1679215/


All Articles