-> How can we write a scala method
whose return type is Nothing
?
-> Do we ever need to write such methods
? Are there any useful scenarios
?
You can't actually return a value of type Nothing
because there are no values of type Nothing
. So the only way to define a function with return type Nothing
is to never return at all.
One example would be a function that just calls itself recursively infinitely. Another would be one that always throws an exception or simply exits the application (sys.exit
's return type is Nothing
).
Actually, Nothing is used in functions which never returns or terminates abnormaly by throwing some exception eg:
scala> def funcReturnNothing : Nothing = throw new RuntimeException("runtime exception")
funcReturnNothing: Nothing
More explanation.
Functions in Scala are co-variant in its return type let's say return type of the function is T
so this function can only return values which are subtype of T
or type of T
and Nothing
is subtype of all other type (Lowest in type chain) So, in actual you can not return anything useful from it but exceptions throwing has a type Nothing
which you can return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With