类型参数不扩展给定类型 [英] Type parameter does not extend given type
本文介绍了类型参数不扩展给定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想定义一个泛型,使其类型参数不扩展给定类型.
I would like to define a generic such that its type parameter does NOT extend a given type.
例如,
trait myTrait[T <: Throwable] {
// ....
}
将定义一个 trait,其中它的类型参数扩展了 Throwable.我想要类似的东西(不是真正的 Scala 代码):
would define a trait where its type parameter extends Throwable. I want something like (not real Scala code):
trait myTrait[T Not(<:) Throwable] {
// ....
}
type 类型参数不扩展 Throwable 的地方.有没有办法在 Scala 中构造这样的概念?
Where the type type parameter does NOT extend Throwable. Is there a way to construct such a notion in Scala?
推荐答案
你可以使用隐式来做这样的事情.这是 Miles Sabin 关于 Scala 语言的一个技巧:
You can do such a thing using implicits. Here's a trick from Miles Sabin on scala-language:
// 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
这篇关于类型参数不扩展给定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文