Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a function that doesn't return in Scala

Tags:

scala

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)

like image 837
antonone Avatar asked Aug 30 '19 05:08

antonone


People also ask

Does Scala function need return?

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.

What is the meaning of => in Scala?

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

Does Scala has void return type?

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.

Can you do += in Scala?

+= 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):


2 Answers

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.

like image 72
Travis Brown Avatar answered Sep 21 '22 17:09

Travis Brown


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
}
like image 22
Brian McCutchon Avatar answered Sep 18 '22 17:09

Brian McCutchon