The Nothing Type : Kotlin

Suneet Agrawal
Jun 15, 2018 · 2 min read

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

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)
}

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")//we are sure sure that personName is not null
println(personName)

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

Nothing

Reference : Kotlin Docs (Nothing Class)
Read my other interesting articles about Kotlin here.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade