簡體   English   中英

Scala:聲明Any => Nothing類型的延續時的編譯錯誤

[英]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()}

在我看來,編譯器應該推斷BNothing ,但事實並非如此。

您無法返回Nothing類型,因為它沒有實例。 任何預期返回Nothing代碼都不能返回。 例如,總是拋出異常的方法可以聲明為什么都不返回。

Java調用void返回是Scala中的Unit

有關更多信息,為什么不看看詹姆斯·伊里(James Iry)所說的關於“無所不能”的內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM