简体   繁体   中英

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. 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

  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. Can someone explain to me what I'm doing wrong?

In caller2, Data is a type parameter, not the class name.

This is probably duped somewhere.

Like here , where @TravisBrown calls it annoying in the extreme .

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. Somebody's linter ought to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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