Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write a scala method which returns Nothing

Tags:

scala

-> 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?

like image 656
oblivion Avatar asked Feb 07 '23 19:02

oblivion


2 Answers

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).

like image 155
sepp2k Avatar answered Feb 16 '23 21:02

sepp2k


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.

like image 43
curious Avatar answered Feb 16 '23 21:02

curious