Scala:声明 Any => 类型的延续时出现编译错误没有什么
此代码给出编译错误:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我指定类型参数,它就会编译:
在我看来,编译器应该推断出
B
是Nothing
,但事实并非如此。It compiles if I specify the type arguments:
It looks to me like the compiler should infer that
B
isNothing
, but it doesn't.您无法返回
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 returnNothing
must never return. For example, a method which always throws exceptions may be declared as returning nothing.A return of what Java calls
void
isUnit
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.