将我的scala升级到最新版本后,我收到了错误:
类型不匹配;发现: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("...")
有什么想法吗?
答案 0 :(得分:2)
failure
过去没有返回类型,然后返回类型为Nothing
。这已被修复为返回Failure
并且与非可变规范更加一致。
但是,您的代码中不需要failure
,因为有例外匹配器(请参阅“例外”标签here),您可以写:
body must throwAn[IllegalArgumentException]
答案 1 :(得分:1)
如消息所示,方法failure
返回Failure
,但您告诉编译器要返回T
。您可以在最后一行(failure
可能曾经做过)中抛出异常。您还可以使用Class[T]
手动传递ClassTag
:
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
}