3

此代码给出编译错误:

import scala.util.continuations._

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

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

错误信息:

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

但是这段代码按预期工作:

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}
}

问题是:为什么 Scala 编译器讨厌类型 Any => Nothing 的延续?

4

2 回答 2

3

如果我指定类型参数,它会编译:

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

在我看来,编译器应该推断BNothing,但事实并非如此。

于 2011-03-19T06:42:50.007 回答
1

您不能返回 type Nothing,因为它没有实例。任何预期返回的代码都Nothing不能返回。例如,总是抛出异常的方法可能被声明为不返回任何内容。

Java 调用的返回voidUnit在 Scala 中。

欲了解更多信息,您为什么不看看 James Iry 所说的“一无所有”

于 2011-03-18T20:24:24.387 回答