Image credit: Unsplash

This article explores the usefulness of Kotlin’s Nothing type in generics. We look at its relationship to Java. To take a concrete example, let’s look at a linked list.

Fig. 1: A LinkedList

A LinkedList wraps some type T . The linked list can either be

A Node<T> with two properties: a payload of T and a next of type LinkedList<T> ; or An EmptyList .

A sealed class enforces that the LinkedList is either type 1 or type 2.

We can readily code up the sealed class and the Node<T> as follows:

A LinkedList definition; the empty list is not defined.

Coding up the empty list is a bit more challenging. All empty lists are the same. So, an empty list is an object . EmptyList must also be a subclass of LinkedList<T> . We might try to write

Code cannot compile; Kotlin objects cannot have type parameters.

Kotlin objects cannot have type parameters. The above code will not compile. Instead, we might try to remove the EmptyList’s type parameter.

Cannot compile; reference to T on line 5 is unresolved.