0

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?

3
  • Why not case class Data(x: Int)? Why the mutable field? Commented Oct 4, 2014 at 2:00
  • It was a pretty arbitrary selection, since it wasn't what I cared about in the overall testing. Commented Oct 4, 2014 at 7:19
  • Your mind should be geared towards case class by default if you don't care. Commented Oct 4, 2014 at 16:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It took a little while, but the explanation makes sense. I do apologize for the duplication as I didn't realize it was a shadow issue (or what that even meant) before reading through the links you provided.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.