The code is following
implicit def orderingList[Int](implicit ord: Ordering[Int]): Ordering[List[Int]] =
new Ordering[List[Int]] {
@scala.annotation.tailrec
def compare(xs: List[Int], ys: List[Int]): Int =
(xs, ys) match {
case (x :: xsTail, y :: ysTail) =>
val c = ord.compare(x, y)
if (c != 0) c else compare(xsTail, ysTail)
case (Nil, Nil) => 0
case (r, Nil) => if (r.forall(_ == 0)) 0 else 1
case (Nil, r) => if (r.forall(_ == 0)) 0 else -1
}
}
it will broken in IDEA and RPEL such as
Welcome to Scala 2.13.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_181).
Type in expressions for evaluation. Or try :help.
scala> implicit def orderingList[Int](implicit ord: Ordering[Int]): Ordering[List[Int]] =
| new Ordering[List[Int]] {
| @scala.annotation.tailrec
| def compare(xs: List[Int], ys: List[Int]): Int =
| (xs, ys) match {
| case (x :: xsTail, y :: ysTail) =>
| val c = ord.compare(x, y)
| if (c != 0) c else compare(xsTail, ysTail)
| case (Nil, Nil) => 0
| case (r, Nil) => if (r.forall(_ == 0)) 0 else 1
| case (Nil, r) => if (r.forall(_ == 0)) 0 else -1
| }
| }
if (c != 0) c else compare(xsTail, ysTail)
^
On line 8: error: type mismatch;
found : c.type (with underlying type Int)
required: Int
case (Nil, Nil) => 0
^
On line 9: error: type mismatch;
found : Int(0)
required: Int
case (r, Nil) => if (r.forall(_ == 0)) 0 else 1
^
On line 10: error: type mismatch;
found : Int(0)
required: Int
case (r, Nil) => if (r.forall(_ == 0)) 0 else 1
^
On line 10: error: type mismatch;
found : Int(1)
required: Int
case (Nil, r) => if (r.forall(_ == 0)) 0 else -1
^
On line 11: error: type mismatch;
found : Int(0)
required: Int
case (Nil, r) => if (r.forall(_ == 0)) 0 else -1
^
On line 11: error: type mismatch;
found : Int(-1)
required: Int
However, when change Int
to A
, it works
What’s the problem?