In Scala absolutely everything needs to have a return type.
println
for example have the return type Unit
because it's a unit of calculations that returns no value.
If everything needs to have a return type then, how would you implement a function like ???
, so that it can be used by any function, no matter what type it needs to return?
Well that is what Nothing
is for, it's a subtype of every other types (as Any
is the top type of every other type), so a function that returns Nothing
can be used anywhere and the type system will always stay consistent.
As you already noticed functions returning Nothing
never return a value. That is because there is no value instenciable for Nothing
.
You can see it as a way to make the compiler "happy" for functions that only throws or stop the app or loop forever.
In case you wonder why we don't use Unit
instead of Nothing
, here is an example:
def notYetImplemented: Unit = throw new Exception()
def myFunc: String = notYetImplemented
This will not compile because Unit
is not a String
or a subtype of String
. So you will need to do:
def myFunc: String = {
notYetImplemented
null
}
Which is not very convenient and for us to write a value to return even taught we will never reach this code.
Cheers