Nothing
Earlier in the book, we saw the TODO()
function:
fun heyThisIsNotDoneYet() {
TODO("implement this function")
}
TODO()
throws an exception with the supplied message. We use this as a more forceful alternative to simply using a TODO
comment to identify incomplete work.
Contrast that with:
fun heyThisIsNotDoneYet(): Int {
TODO("implement this function")
}
On the surface, this would seem like it could not possibly compile. We have set up heyThisIsNotDoneYet()
to return an Int
, yet we have no return
statement or anything else to return a value. After all, if we skipped the TODO()
, we definitely would get a compilation error:
fun heyThisIsNotDoneYet(): Int {
// TODO implement this function
}
So, what is it about TODO()
that allows it to somehow complete the body of a function that returns something, while not returning anything?
The answer is: nothing. Or, more accurately, Nothing
.
Nothing
: It’s On the Bottom
Earlier in the book, we saw Any
. Any
in Kotlin is analogous to Object
in Java: it is the root type from which all other types inherit. In truth, Any
is even more widespread in Kotlin than Object
is in Java, because all Kotlin types extend Any
, whereas primitives (e.g., int
) and arrays (e.g., int<>
) do not extend Object
in Java.
Nothing
has no Java analogue and is on the far other end of the inheritance spectrum. Effectively, Nothing
is a sub-type of all other types. It is a sub-type of Any
. It it a sub-type of String
. It is a sub-type of Axolotl
.
Nothing
has no instances. It is impossible to create instances of Nothing
, as it has a private
constructor.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.