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

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)

As looking at the above method, we are pretty sure that the method will never return and will throw an exception before that. The return type can be denoted by Nothing class. We could have used void type also in place of Nothing in the same method but in that case, the compiler won’t be sure that the method will return or not. But if we replace the return type by Nothing, the compiler will be sure that this will never return.

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

As we know that throw is an expression in Kotlin and can be used as a part of Elvis operator also.

val personName = person.name ?: throw IllegalArgumentException("Name required")

The above code can be replace with

val personName = person.name ?: throwException("Name required")

That’s it. So What did we learn today?


Reference : Kotlin Docs (Nothing Class)

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.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store