简体   繁体   English

Scala:声明Any => Nothing类型的延续时的编译错误

[英]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? 现在的问题是:为什么Scala编译器恨型延续的任何=>什么都没有?

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. 在我看来,编译器应该推断BNothing ,但事实并非如此。

You can't return the type Nothing , because it has no instances. 您无法返回Nothing类型,因为它没有实例。 Any code that is expected to return Nothing must never return. 任何预期返回Nothing代码都不能返回。 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. Java调用void返回是Scala中的Unit

For more information, why don't you see what James Iry had to say about Getting to the Bottom of Nothing at All . 有关更多信息,为什么不看看詹姆斯·伊里(James Iry)所说的关于“无所不能”的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM