[英]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.