What if I say there is a class called Nothing in Koltin.
And What does it do? Nothing.

This post was originally posted at https://agrawalsuneet.github.io/blogs/the-nothing-type-kotlin/ and reposted on Medium on 15th Jun 2018.

The time I read about the class Nothing for the first time, it sounds interesting to me. This class has no instance and it is used to represent a value which never exists. This class is also used to represent a return type from a method that will never return.

Confused? Let me explain.

If we use null to initialize a value of an inferred type and there is no other information that can be used to determine a more specific type, the compiler considers it as Nothing? type.

val variable = null
//compiler will read this as
// val variable : Nothing? = null
val list = listOf(null)
//compiler will read this as
//val list : List<Nothing?> = listOf(null)

The type of variable will be Nothing?. Or even if we initialize a list of nulls, the compiler will consider it as a list of Nothing? type.

Nothing has no type and can also be used to mark code locations that can never be reached. Let’s say we have a method which throws an exception. The return type of that method would be Nothing type.

fun throwException(message: String): Nothing {
throw IllegalArgumentException(message)
}

Please continue reading at https://agrawalsuneet.github.io/blogs/the-nothing-type-kotlin/

And we are done. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.