如何解决由方法

时间:2017-07-03 00:02:49

标签: scala

使用以下代码,> =和< =方法使用隐式参数和上下文绑定,它们基本相同。

@Test
def testOrdering(): Unit = {
  class Box[T](val data: T) {
    def >= (that: Box[T])(implicit ord: Ordering[T]): Boolean = {
      val comp = ord.compare(data, that.data)
      comp >= 0
    }
    def <=[T :Ordering] (that: Box[T]): Boolean = {
      val ord = implicitly[Ordering[T]]
      //compile error in the following code
      val comp = ord.compare(data, that.data)
      comp <= 0
    }
  }
}

然而,&lt; =方法中的T与Box [T]中定义的T不同,因此在&lt; =。(val comp = ord.compare(data, that.data)中存在编译错误,数据和该数据是不同的类型。)

我会问是否可以解决这个问题:

(1)T在Box [T]

中定义

(2)在方法中使用上下文绑定,例如&lt; =

2 个答案:

答案 0 :(得分:2)

您对>=的定义就是如何做到的。

def <= (that: Box[T])(implicit ord: Ordering[T]): Boolean = {
  val comp = ord.compare(data, that.data)
  comp <= 0
}

阴影T在这里永远不会起作用,因为你告诉编译器有一个另一个类型参数,而不是T中定义的Box[T],即使它有相同的名字。并且您只能在类型参数的定义站点使用上下文绑定语法。

答案 1 :(得分:1)

如果添加类型别名type OrderingT[A] = Ordering[T],您仍然可以使用上下文绑定。注意类型参数A基本上是如何被抛弃的。但是,当然,您将为每个方法添加一个无用的类型参数(在此示例中名为_)。

def testOrdering(): Unit = {
  class Box[T](val data: T) {
    type OrderingT[A] = Ordering[T]

    def >=[_: OrderingT](that: Box[T]): Boolean = {
      val comp = Ordering[T].compare(data, that.data)
      comp >= 0
    }
    def <=[_: OrderingT](that: Box[T]): Boolean = {
      val comp = Ordering[T].compare(data, that.data)
      comp <= 0
    }

  }
}