2013-07-05 44 views
1

我想寫一個函數,它將在未來處理異常並返回新的未來,但我遇到了麻煩,不能使作爲簽名要求的錯誤消息斯卡拉類型不匹配:default.type(與底層類型A1 => B1)

scala> def composeHandlingFuture[T](fut: Future[T], default: T): Future[T] = 
    | fut recover { case e: Exception => default } 
<console>:19: error: type mismatch; 
found : default.type (with underlying type A1 => B1) 
required: T 
     fut recover { case e: Exception => default } 
             ^

意識不default.type等於T?它與type A1 => B1有什麼關係?

任何幫助表示讚賞。

P.S.我使用Scala的2.10.1

+0

我不能解釋錯誤消息,但刪除顯式返回類型可以讓你定義函數沒有它抱怨 – theon

+0

是的,但返回類型變成scala.concurrent.Future [Any],這不是我想要的 – Zotov

+0

啊,是的,剛纔也注意到了。 IntelliJ說謊並且說返回類型是'Future [T]' – theon

回答

3

的問題來自於打字員階段。如果我們使用-Xprint:打字員,然後我們就可以看到問題:

def composeHandlingFuture[T >: Nothing <: Any](fut: scala.concurrent.Future[T], default: T): scala.concurrent.Future[T] = fut.recover[T](({ 
     @SerialVersionUID(0) final <synthetic> class $anonfun extends scala.runtime.AbstractPartialFunction[Throwable,T] with Serializable { 
     /////// Init method ////// 

     final override def applyOrElse[A1 >: Nothing <: Throwable, B1 >: T <: Any](x1: A1, default: A1 => B1): B1 = ((x1.asInstanceOf[Throwable]: Throwable): Throwable @unchecked) match { 
      case (e @ (_: Exception)) => <error: value default> // your argument comes here, but name clash happens 
      case (defaultCase$ @ _) => default.apply(x1) 
     }; 


     //// IsDefinedAt method //// 
    } 

的問題是在PartialFunction,第二個參數aplyOrElse也被稱爲defaultA1 => B1類型。 Here它是在斯卡拉編譯器Typer階段,所以你可以讓我猜的票

0

奇怪,當我改名爲default變量,樣樣精編:

scala> def composeHandlingFuture[T](fut: Future[T], x: T): Future[T] = 
    | fut recover { case e: Exception => x } 
composeHandlingFuture: [T](fut: scala.concurrent.Future[T], x: T)scala.concurrent.Future[T]