[英]Scala: compilation error when declaring continuation of type Any => Nothing
此代码提供编译错误:
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编译器恨我型延续的任何=>什么都没有?
如果我指定类型参数,它会编译:
shift[Unit, Nothing, Nothing] {c: (Unit => Nothing) => c()}
在我看来,编译器应该推断B
是Nothing
,但事实并非如此。
您无法返回Nothing
类型,因为它没有实例。 任何预期返回Nothing
代码都不能返回。 例如,总是抛出异常的方法可以声明为什么都不返回。
Java调用void
返回是Scala中的Unit
。
有关更多信息,为什么不看看詹姆斯·伊里(James Iry)所说的关于“无所不能”的内容 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.