Declare a function that doesn't return in Scala

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
}

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)

}

Tags:

Scala