Any, Nothing, and Unit in Kotlin
In this short post, we’ll take a look at some of the special types in Kotlin. These types are Any
, Nothing
, and Unit
. You may have used some or all of them but may not know the exact difference between them. If that’s the case then read on!
Any
The official documentation of Any
states:
The root of the Kotlin class hierarchy. Every Kotlin class has Any as a superclass.
This means Any
is the parent class of any class you define in Kotlin. This means if you follow the chain of parents of a class you will finally end up at Any
. It’s the exact equivalent of Object
in Java.
Here is the definition of Any
. Based on the above paragraph and the following definition, every class in Kotlin has methods equals
, hashCode
and toString
.
public open class Any {
public open operator fun equals(other: Any?): Boolean
public open fun hashCode(): Int
public open fun toString(): String
}
Nothing
Based on the official documentation of Nothing
You can use Nothing to represent “a value that never exists”: for example, if a function has the return type of Nothing, it means that it never returns (always throws an exception).
Simply put we usually use Nothing
as the return type of a function to indicate that the function always throws an exception.
Here is the definition of Nothing
.
public class Nothing private constructor()
The above definition means that you cannot instantiate an instance of this class. It also means that no other class can inherit it.
An example usage ofNothing
is in the error
function which is part of the Kotlin standard library:
public inline fun error(message: Any): Nothing = throw IllegalStateException(message.toString())
As can be seen, because the error
function always throws an exception, its return type is of type Nothing
meaning that this function never completes successfully.
Unit
The definition of Unit
is as follows:
public object Unit {
override fun toString() = "kotlin.Unit"
}
Unit
is the same thing as void
in Java or C. When the return type of a function is Unit
it means that the function does not return anything.
In Kotlin, the default return type of a function is Unit
meaning that if you do not specify the return type of a function explicitly then the Kotlin compiler uses Unit
as the return type.
That’s all!