类型参数不会扩展给定的类型
我想定义一个泛型,使其类型参数不扩展给定的类型。
例如,
trait myTrait[T <: Throwable] {
// ....
}
将定义其类型参数扩展Throwable的特征。 我想要的东西(不是真正的Scala代码):
trait myTrait[T Not(<:) Throwable] {
// ....
}
类型类型参数不能扩展Throwable。 有没有办法在Scala中构建这样的概念?
你可以用implicits来做这样的事情。 以下是迈克尔萨宾关于scala语言的一个技巧:
// Encoding for "A is not a subtype of B"
trait <:!<[A, B]
// Uses ambiguity to rule out the cases we're trying to exclude
implicit def nsub[A, B] : A <:!< B = null
implicit def nsubAmbig1[A, B >: A] : A <:!< B = null
implicit def nsubAmbig2[A, B >: A] : A <:!< B = null
// Type alias for context bound
type NOT[T] = {
type Lambda[U] = U <:!< T
}
// foo does not accept T of type Unit
def foo[T : NOT[Unit]#Lambda](t : T) = t
链接地址: http://www.djcxy.com/p/51021.html