scala - 类型参数不扩展给定类型

标签 scala

我想定义一个泛型,使其类型参数不扩展给定类型。

例如,

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/

相关文章:

scala - 使用 scala.tools.nsc.Global 解析 Scala 源代码

mysql - 获取表 A 中引用表 B 的行数

scala - 还有什么其他方法而不是在spark scala中使用collect()

Scala LinkedHashMap.toMap 保留顺序?

scala - Scala 的 Metaphone 或 Soundex

scala - sbt、 jetty 和类路径

scala - sbt-assembly 排除 dependsOn 依赖

scala - 下载时sbt卡住了

design-patterns - 双折功能图案

scala - 将 Elasticsearch 5.5批量提取API与Spark流一起使用时发生NullPointerException