Scala:声明 Any => 类型的延续时出现编译错误没有什么

发布于 2024-10-24 03:20:06 字数 748 浏览 6 评论 0原文

此代码给出编译错误:

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 => 的延续;没有什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

垂暮老矣 2024-10-31 03:20:06

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

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

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

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.

合久必婚 2024-10-31 03:20:06

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

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

欲了解更多信息,为什么不看看 James Iry 对 一无所有

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文