【问题标题】:Scala: compilation error when declaring continuation of type Any => NothingScala:声明类型为 Any => Nothing 的延续时出现编译错误
【发布时间】:2011-03-18 17:55:21
【问题描述】:

此代码给出编译错误:

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 编译器讨厌 me Any => Nothing 类型的延续?

【问题讨论】:

  • 我想知道loop 是否正在做你认为它正在做的事情。尝试改写() => looploop _
  • loop 的唯一目的是无限递归(并调用其他方法,但为了简化示例,省略了这段代码)。

标签: scala continuations


【解决方案1】:

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

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

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

【讨论】:

  • shift[Unit, Nothing, Nothing] {c => c()} 也可以。这绝对是 continuation 插件中的一个错误。
【解决方案2】:

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

Java 调用 void 的返回值在 Scala 中是 Unit

要了解更多信息,您为什么不看看 James Iry 对Getting to the Bottom of Nothing at All 的看法。

【讨论】:

  • 是的,但我不想返回。看一下循环方法。它永远不会回来。我的问题是为什么我不能宣布这样的延续。
猜你喜欢
  • 2013-07-01
  • 1970-01-01
  • 2023-01-08
  • 2020-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
  • 1970-01-01
相关资源
最近更新 更多