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?
case class Data(x: Int)? Why the mutable field?case classby default if you don't care.