E. Verda
E. Verda

Reputation: 285

Scala: compilation error when declaring continuation of type Any => Nothing

This code gives compilation error:

import scala.util.continuations._

object CTest {
    def loop: Nothing = reset {
        shift {c: (Unit => Nothing) => c()}
        loop
    }

   def main(argv: Array[String]) {loop}
}

Error message:

    error: type mismatch;
 found   : ((Unit) => Nothing) => (Unit) => Nothing
 required: ((Unit) => B) => (Unit) => Nothing

But this code works as expected:

import scala.util.continuations._

object CTest {
    def loop: Nothing = reset {
        shift {c: (Unit => Any) => c.asInstanceOf[Unit => Nothing]()}
        loop
    }

   def main(argv: Array[String]) {loop}
}

The question is: why Scala compiler hates me continuations of type Any => Nothing?

Upvotes: 3

Views: 1425

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170713

It compiles if I specify the type arguments:

shift[Unit, Nothing, Nothing] {c: (Unit => Nothing) => c()}

It looks to me like the compiler should infer that B is Nothing, but it doesn't.

Upvotes: 3

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297155

You can't return the type Nothing, because it has no instances. Any code that is expected to return Nothing must never return. For example, a method which always throws exceptions may be declared as returning nothing.

A return of what Java calls void is Unit in Scala.

For more information, why don't you see what James Iry had to say about Getting to the Bottom of Nothing at All.

Upvotes: 1

Related Questions