我想定义一个泛型,使其类型参数不扩展给定类型。
例如,
trait myTrait[T <: Throwable] {
// ....
}
将定义一个特征,其类型参数扩展 Throwable。我想要类似的东西(不是真正的 Scala 代码):
trait myTrait[T Not(<:) Throwable] {
// ....
}
类型类型参数不扩展 Throwable 的地方。有没有办法在 Scala 中构建这样的概念?
最佳答案
你可以使用隐式来做这样的事情。这是 Miles Sabin 关于 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
关于scala - 类型参数不扩展给定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7781782/