【问题标题】:How to define a trait so that we extend with classes that have context bounds?如何定义一个特征,以便我们使用具有上下文边界的类进行扩展?
【发布时间】:2014-10-02 22:18:24
【问题描述】:

假设我希望能够做到:

trait MyTrait[T: Numeric] {
  val numeric = implicitly[Numeric[T]]
  import numeric.mkNumericOps
  // more code
}

然后扩展

class MyClass[T: Numeric] extends MyTrait[T] {
  // code
}

你知道“特征不能有带有上下文边界的类型参数”。

有什么东西在语法上非常接近这个,并且做同样的事情吗?

【问题讨论】:

标签: scala functional-programming


【解决方案1】:

像这样:

trait MyTrait[T] {
  val numeric: Numeric[T]
  import numeric.mkNumericOps
  // more code
}

class MyClass[T: Numeric] extends MyTrait[T] {
  val numeric = implicitly[Numeric[T]]
  // code
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多