Blog / June 15, 2018 / 2 mins read / By Suneet Agrawal

The Nothing Type : Kotlin

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

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

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

//we are sure that personName is not null
println(personName)

And the compiler will know that the execution will not continue if the value of personName is null

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

Nothing

Comments