2014-04-17 31 views
0

升級我的斯卡拉最新版本,我得到這個錯誤後:升級到最新版本後:org.specs2.execute.Failure要求:T

type mismatch; found : org.specs2.execute.Failure required: T

我的代碼:

def shouldThrow[T <: Exception](exClazz: Class[T])(body: => Unit): T = { 
    try { 
     body 
    } catch { 
     case e: Throwable => 
     if (e.getClass == exClazz) return e.asInstanceOf[T] 
     val failure = new Failure("Expected %s but got %s".format(exClazz, e.getClass), "", new Exception().getStackTrace.toList, org.specs2.execute.NoDetails())             
     val rethrown = new FailureException(failure) 
     rethrown.initCause(e) 
     throw rethrown 

    } 
    failure("Exception expected, but has not been thrown") 
    } 

我在最後一行得到這個錯誤failure("...")

任何想法什麼是布萊恩?

回答

1

如消息所示,方法failure返回Failure,但您告訴編譯器您想返回T。你可以在最後一行拋出一個異常(可能用於做failure)。您也可以通過避免使用ClassTag手動傳遞Class[T]

def shouldThrow[T <: Exception](body: => Unit)(implicit ct: ClassTag[T]): T = { 
    ... // as before 
    case e: Throwable => 
    val exClass = ct.runtimeClass 
    ... // as before 
} 

// usage 
shouldThrow[IOException] { 
    // body 
} 
2

在使用沒有返回類型來定義可變規格failure,然後返回類型爲Nothing。這已被固定爲返回Failure,並且與非可變規格更加一致。

但是你不需要failure在你的代碼,因爲也有例外的匹配(見「例外」選項卡here),你可以這樣寫:

body must throwAn[IllegalArgumentException]