【问题标题】:Type constraints on the companion object of a type parameter in scalascala中类型参数的伴随对象的类型约束
【发布时间】:2013-02-28 17:58:33
【问题描述】:

我想定义一个名为 ExtendedNumber 的参数化类,它将采用某种形式的整数,例如 Int 或 Byte,并将其扩展为包括无穷大、-infinity 和 null。特别是,我想用 MaxValue 来表示无穷大。如果 MaxValue 是静态成员,我相信我可以这样做:

class ExtendedNumber[T <: {val MaxValue : T}] {
  val infinity = T.MaxValue
  ...
}

但是,由于 MaxValue 是在伴随对象中定义的,我相信我需要对伴随对象进行类型约束。这可能吗?我也对一般问题的其他解决方案持开放态度。

【问题讨论】:

  • 我不相信你可以直接约束伴随对象,因为伴随对象并不是类型系统的一部分,而是当类和对象之间存在某些词法关系时访问规则的放宽.同伴也反映在隐含的解决规则中,我想,你可以以某种方式参与其中。但我会考虑使用绑定的上下文将承载infinity-infinity 等值(也可能为零)的值传达给ExtendedNumber

标签: scala


【解决方案1】:

一般的解决方案是添加一个类型类,例如:

trait ExtendedNumber[T] {
  def infinity: T
}

implicit object extendedInt extends ExtendedNumber[Int] {
  def infinity = Int.MaxValue
}

def foo[T](v: T)(implicit en: ExtendedNumber[T]) = v == en.infinity

【讨论】:

    猜你喜欢
    • 2017-01-08
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    相关资源
    最近更新 更多