简体   繁体   English

Scala Context Bounds语法错误

[英]Scala Context Bounds syntax error

I'm trying to see if I understand Context Bounds in Scala, so I wrote up a little dummy example to see how the implicit variables get passed around. 我试图查看我是否了解Scala中的Context Bounds,所以我写了一个虚拟的示例来了解隐式变量如何传递。 My code is below. 我的代码如下。

  class Data(_x : Int) {
    var x = _x
  }

  class DataOrdering extends Ordering[Data] {
    def compare(d1 : Data, d2 : Data) : Int = d1.x - d2.x
  }

  def globalCompare[Data : Ordering](d1 : Data, d2 : Data) {
    println("Global compare: " + implicitly[Ordering[Data]].compare(d1, d2))
  }

  def caller()(implicit d : Ordering[Data]) {
    println("Caller")
    globalCompare(new Data(5), new Data(100))
  }

  // Error method here
  def caller2[Data : Ordering]() {
    println("Caller2")
    globalCompare(new Data(50), new Data(100))
  }

  def main() {
    implicit val dataOrdering : DataOrdering = new DataOrdering
    caller
    caller2
  }

  main

The caller() method works as I expect in calling globalCompare, but caller2() gives me a compile error caller()方法在调用globalCompare时按预期工作,但是caller2()给我一个编译错误

  error: class type required but Data found
  globalCompare(new Data(50), new Data(100))
                    ^

  error: class type required but Data found
  globalCompare(new Data(50), new Data(100))
                                  ^

I expected caller() and caller2() to be equivalent, but I seem to be missing something. 我期望caller()和caller2()是等效的,但是我似乎缺少了一些东西。 Can someone explain to me what I'm doing wrong? 有人可以向我解释我在做什么错吗?

In caller2, Data is a type parameter, not the class name. 在caller2中, Data是类型参数,而不是类名称。

This is probably duped somewhere. 这可能在某个地方被骗了。

Like here , where @TravisBrown calls it annoying in the extreme . 就像这里 ,@ TravisBrown称其为极端 烦人

I don't know whether it's more annoying when you're shadowing a concrete type name. 我不知道在遮盖具体类型名称时是否更令人讨厌。 I wonder if Xlint would have warned you about that. 我不知道Xlint是否会Xlint警告您。 Somebody's linter ought to. 应该有人的轻信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM