antekone
antekone

Reputation: 2125

Declare a function that doesn't return in 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)

Upvotes: 14

Views: 919

Answers (4)

ChiragB
ChiragB

Reputation: 3

Use nothing, its primary usage is to signal termination.(Scala official documentation https://www.scala-lang.org/api/2.9.3/scala/Nothing.html.) Normally nothing doesn't returns anything not even computation and used for methods which continuously throws exception.

Upvotes: 0

Dmytro Orlov
Dmytro Orlov

Reputation: 186

Some real world example:

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import zio._

object Server extends App {
  val program: ZIO[Any, Throwable, Nothing] =
    UIO(ActorSystem()).bracket(terminateSystem) { implicit system =>
      implicit val mat = ActorMaterializer()
      for {
        _ <- IO.fromFuture { _ =>
          Http().bindAndHandle(routes, "localhost", 8080)
        }
        _ <- IO.never
      } yield ()
    }

  def run(args: List[String]) = program.fold(_ => 1, _ => 0)

}

Upvotes: 3

Brian McCutchon
Brian McCutchon

Reputation: 8584

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
}

Upvotes: 10

Travis Brown
Travis Brown

Reputation: 139048

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.

Upvotes: 11

Related Questions