It should be apparent, even to the casual reader of this blog, that I really like Kotlin as a language. One of the reasons is its Type Hierarchy, which is both very easy to work with and extremely powerful. It is also quite close to the Java Type System, so the interoperability is excellent.To take full advantage of Kotlin Type Hierarchy is essential to understand how these three special types do work.We will look in detail at Unit, Nothing, Any and compare their use against Java corresponding classes.Finally, we also consider null and how types ending with ? fit into these categories.
This function would have returned Unit if it hadn’t thrown an Exception. Now if you guess that this is exactly the case of returning Nothing, you are right. Let’s look at the actual implementation of it:
Since it has a private constructor and it is not called from the class itself, this means that there can’t be any instances of Nothing. Nothing is also a bottom type, which means that it is a subtype of every other type (including Unit).
Before going to Nothing, first, let’s look at its sibling Unit.
Unit in Kotlin corresponds to the void in Java. Like void, Unit is the return type of any function that does not return any meaningful value, and it is optional to mention the Unit as the return type. But unlike void, Unit is a real class (Singleton) with only one instance.
Nothing is a type in Kotlin that represents “a value that never exists”, that means just “no value at all”.
Nothing can be used as the return type of a function that never returns the code execution — like, looped forever or always throws Exception. Don’t get confused because Java does not have anything similar to the Nothing type.
Object is the root of the class hierarchy in Java, every class has Object as a superclass. In Kotlin theAny type represents the super type of all non-nullable types.It differs to Java’s Object in 2 main things:
In Java, primitives types aren’t type of the hierarchy and you need to box them implicitly, while in Kotlin Any is a super type of all types.
Any can’t hold the null value, if you need null to be part of your variable you can use the type Any?
java.lang.Object methods toString, equals and hasCode are inherited fromAny while to usewait and notify you will need to cast your variable to Object to use them.
In Java if we want that a function does return nothing we use void, Unit is the equivalent in Kotlin.The main characteristics of Unit against Java’s void are:
Unit is a type and therefore can be used as a type argument.Only one value of this type exists.It is returned implicitly. No need of a return statement.