What can `Nothing` be used for?

Viewed 180

I am specifically asking for the non-nullable type Nothing.

I do know that Nothing? allows us to, for example, filter null to make an overload unambiguous, but I'm struggling to think of instances where Nothing would be useful.

Nothing? can have exactly one value, null. So Nothing can have exactly no value. What's the point? Why not simply use Unit?

2 Answers

1. Nothing is the counterpart to Any?

Just as Any? is the base type of any other type, Nothing is the sub type of any other type (even the nullable ones).

Knowing this it becomes clear that s will be of type String in the following example, given name is a String?.

val s = name ?: throw IllegalArgumentException("Name required")

The throw expression returns Nothing, and the common base type of String and Nothing is String. That's what we want, because that's the type we want to work with.

If we would use Unit instead of Nothing the common base type would be Any, which is certainly not what we want, because it would require a cast to String afterward.

That makes sense too, because if the exception will be thrown execution cannot continue there, thus s wouldn't be used any further anyway.

2. Nothing marks code locations that can never be reached

fun foo() {
   throw IllegalArgumentException("...")
   println("Hey") // unreachable code
}

3. Type inference

If null is used to initialize a value of an inferred type and there's no other information to determine a more specific type, the inferred type will be Nothing?.

val x = null           // 'x' has type `Nothing?`
val l = listOf(null)   // 'l' has type `List<Nothing?>

Further reading

Nothing is used to tell the compiler that it will never return. For example,


fun main() {
   var name: String? = null
   val notNullName = name ?: fail("name was null")
   println(notNullName)
}

fun fail(message: String): Nothing {
  throw RuntimeException(message)
}

fun infiniteLoop(): Nothing {
   while (true) {
     // Nothingness
   }
}
Related