Is it possible to declare a "no return" function in Scala? I.e.
def abort(): ! = {
System.exit(1);
}
(The !
in this example is taken from Rust, and it means: entering this function is a one-way trip and we'll never return from it)
The Scala programming language, much like Java, has the return keyword, but its use is highly discouraged as it can easily change the meaning of a program and make code hard to reason about.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
In Scala we use the Unit return type to indicate "no return value." This is a "void" function. The void keyword is not used. Return An empty "return" statement can be used in a method that returns a Unit type.
+= and similar operators are desugared by the compiler in case there is a + defined and no += is defined. (Similarly works for other operators too.) Check the Scala Language Specification (6.12. 4):
This is exactly what the Nothing
type represents—a method or expression that will never return a value. It's the type of an expression that throws an exception, for example:
scala> :type throw new Exception()
Nothing
Scala also provides a special ???
operator with this type, which is commonly used to get code to typecheck during development.
scala> :type ???
Nothing
Nothing
is a subtype of everything else, so you can use an expression of type Nothing
anywhere any type is expected.
Use Nothing:
def loop: Nothing = loop
Expressions of this type cannot return normally, but can go into infinite loops or throw exceptions. However, you can't use Nothing in your example, since System.exit has a signature saying it returns Unit. Instead, you could try something like this to make the compiler happy:
def abort(): Nothing = {
System.exit(1);
??? // Unreachable
}
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