如何将Scala方法参数限制为classOf [Exception]或classOf [Exception的子类型]

Jan*_*cki 2 types scala exception

如何声明expectedException以便只传递异常和子类?目前我正在使用expectedException: Any.

细节.

我有一个像这样调用的测试实用程序方法,

assertExceptionThrown("En-passant should be rejected when the previous move was not a double advance", classOf[UnreachablePositionException] ) {
  e.rejectIllegalMove(EnPassant("e5", "d6"))
}
Run Code Online (Sandbox Code Playgroud)

第一个参数列表的第二个参数是classOf [SomeException].这是测试方法的签名,

  // TODO: Restrict expectedException to Exception or subclass
  def assertExceptionThrown(assertion: String, expectedException: Any)(b:  => Unit) {
Run Code Online (Sandbox Code Playgroud)

我的问题是如何声明expectedException,以便只传递异常和子类?目前我正在使用expectedException:Any.

测试特征的完整来源在这里, https://github.com/janekdb/stair-chess/blob/master/src/test/Test.scala

dhg*_*dhg 10

使用泛型:

def assertExceptionThrown[T <: SomeException](assertion: String, expectedException: Class[T])(b:  => Unit)
Run Code Online (Sandbox Code Playgroud)

这表示T来自expectedException必须的类型SomeException或其子类.

示范:

class A
class B extends A
def f[T <: A](x: Class[T]) {}   // f accepts Class[A] or a Class[subclass of A]

f(classOf[A])   // fine
f(classOf[B])   // fine
f(classOf[Int]) // error: inferred type arguments [Int] do not conform to method f's type parameter bounds [T <: A]
Run Code Online (Sandbox Code Playgroud)