2011-03-18 55 views
3

該代碼給出編譯錯誤:斯卡拉:申報時編譯錯誤類型的延續任何=>沒有

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 co Any類型的ntinuations => Nothing?

+0

我不知道'loop'是否在做你認爲正在做的事。試着寫'()=> loop'或'loop _'來代替。 – 2011-03-18 23:54:37

+0

'loop'的唯一目的是無限地遞歸(並調用另一個方法,但爲了簡化示例,省略了這段代碼)。 – 2011-03-19 00:21:27

回答

3

它編譯如果我指定類型參數:

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

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

+1

'shift [Unit,Nothing,Nothing] {c => c()}'也可以。它絕對是continuations插件中的一個bug。 – 2011-03-19 08:53:08

1

您不能返回類型Nothing,因爲它沒有實例。任何預計返回Nothing的代碼都不能返回。例如,總是拋出異常的方法可能被聲明爲不返回任何內容。

Java調用void返回的是斯卡拉的Unit

欲瞭解更多信息,爲什麼你看不到詹姆斯·伊裏關於Getting to the Bottom of Nothing at All要說什麼。

+0

是的,但我不想**返回**沒有。看看循環方法。它永遠不會返回。我的問題是爲什麼我不能宣佈這樣的延續。 – 2011-03-18 21:33:33