What are the Any and Nothing classes in Kotlin?
Any class
Kotlin is an object-oriented programming language that uses a singly rooted hierarchy. It means that all classes in Kotlin inherit from a single class called Any which is at the root.
Thus, the class Any can also be referred to as the superclass of every other class in Kotlin. It is similar to the Object superclass in Java. The following code checks if an integer instance belongs to the Any class.
fun main() {val anInt: Int = 3if (anInt is Any) {println("The Int instance does belong to the Any type")} else {println("The Int instance DOES NOT belong to the Any type")}}
Dealing with null types
The Any class is a non-nullable type, which means that the compiler will throw an error if we try to assign a null value to it:
fun main() {val aNullAny: Any = null}
However, if we need to deal with null types, we can use Any?:
fun main() {val aNullAny: Any? = nullprintln(aNullAny)}
Casting to Any
Since Any is at the root of the hierarchy, all types can be Any type. This casting can also be done implicitly. For example, in the following code, we assign a string to an instance of Any type and then print it.
fun main() {val anAnyInstance: Any = "hello world"println("Any Instance: $anAnyInstance")}
Nothing class
The Nothing class is a class in Kotlin that indicates the absence of a type. The keyword Nothing can be used to represent a value that never exists. It is Kotlin's equivalent to Java's void type.
Private initializer
An instance of Nothing cannot be initialized since it has a private constructor. For example, running the following code will throw an error:
fun main() {val nothingInstance = Nothing()}
Using Nothing as function return type
The Nothing type is usually used as the return type of a function. The function with type Nothing never returns a value. It either always throws an exception or enters an infinite loop. The following example prints a line to the console and then throws an Exception that terminates the function. You may run the code to see how it behaves.
fun nothingTest(): Nothing {println("Function nothingTest() is called")throw Exception("this function will always need to throw an error to terminate")}fun main() {nothingTest()}
Free Resources