4

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

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.