Nothing & Any Flashcards

KOTLIN › Types & Classes

What is Nothing in Kotlin and can you ever create an instance of it?
Nothing is the bottom type: it is a subtype of every other type, and it has no instances. A function that returns Nothing never returns normally -- it always throws or loops forever.
Where does Any sit in Kotlin's type hierarchy, and how does it relate to Java's Object?
Any is the root of all non-nullable types in Kotlin. It maps to java.lang.Object at the JVM level, but Any only declares equals(), hashCode(), and toString(). Any? (nullable Any) is the true top of the whole hierarchy.
Why is throw an expression in Kotlin rather than a statement?
throw has type Nothing, which is a subtype of every type. That lets it appear anywhere an expression is expected -- on the right of elvis ?:, inside a when branch, or as the body of a single-expression function -- without a type mismatch.
What is Nothing? and what values can it hold?
Nothing? can hold exactly one value: null. It is the type the compiler infers when you write val x = null without an explicit type annotation. It is a subtype of every nullable type.
Why can emptyList() assign to List<String> without an explicit type argument?
emptyList() is fun <T> emptyList(): List<T> -- the compiler infers T from the call site. Under the hood it returns a singleton object typed List<Nothing>. Because Nothing <: String and List is covariant (out T), that List<Nothing> is assignable to List<String>.
What does TODO() return and why does it compile in any context?
TODO() returns Nothing because it always throws NotImplementedError. Since Nothing is a subtype of every type, the compiler accepts it wherever any return type is expected.
What is the difference between Unit and Nothing?
Unit is a type with exactly one value (Unit) -- it means the function returns but its return value carries no information, like Java's void. Nothing means the function *never* returns at all.
What type does the compiler infer for val x = null?
The compiler infers Nothing?, because null has no more specific type. You almost always want an explicit annotation like val x: String? = null so the variable is usable.
How does Nothing enable exhaustive when on a sealed hierarchy without an else branch?
If a sealed when is used as an expression, every branch must return a value. A throw branch has type Nothing, which is a subtype of the expected type, so it satisfies the compiler. And because the hierarchy is sealed, covering all subtypes makes else unnecessary.

Back to Nothing & Any