Nothing & Any Interview Questions
KOTLIN › Types & Classes
What are Any, Unit and Nothing in Kotlin?
What a strong answer covers: Any is the root of all non-null types, like Object in Java, with equals, hashCode and toString. Unit is a type with a single value, returned by functions that return nothing useful, like void but a real object. Nothing has no values: a function returning Nothing never returns normally, it always throws or loops forever.
Why does throw have the type Nothing, and how does that make the Elvis operator work for early exits?
What a strong answer covers: Nothing is a subtype of every type, so an expression of type Nothing fits anywhere. That's why val name = user.name ?: throw IllegalStateException() or ?: return compiles: the right side has type Nothing, the overall type stays String, and the compiler knows code after it is unreachable. TODO() also returns Nothing.
What is Nothing? used for, and why is emptyList() able to be assigned to List<String>?
What a strong answer covers: The only value of type Nothing? is null, so val x = null infers Nothing?. emptyList() returns List<Nothing> internally (as the object EmptyList), and because List is covariant (out E) and Nothing is a subtype of String, List<Nothing> is a subtype of List<String>.
How does Nothing help with sealed hierarchies and generic types, for example a Result type with Success and Failure?
What a strong answer covers: With a covariant sealed class Result<out T>, Failure can extend Result<Nothing>, so a single Failure object is assignable to Result<User> and Result<Int> alike without its own type parameter. The same trick gives you a singleton Loading state in UiState<out T>.
Any vs Any? vs a generic T: what does each allow, and why might fun <T> foo(x: T) accept null even if you didn't intend it?
What a strong answer covers: A type parameter T has an implicit upper bound of Any?, so foo(null) compiles. To forbid null, bound it: <T : Any>. Any accepts any non-null value but loses type information; generics keep the caller's type. A strong answer also mentions definitely non-null types (T & Any) for overriding Java generic methods.