Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Scala's RichInt extends Comparable[Int] instead of Comparable[RichInt]?

Why does Scala's RichInt extends Comparable[Int] instead of Comparable[RichInt]?

I'm new to Scala. When browsing Scala library code, I noticed that class RichInt extends ScalaNumberProxy[Int], ScalaNumberProxy extends OrderedProxy, OrderedProxy extends Ordered, and Ordered extends java.lang.Comparable. So my understanding is that RichInt (indirectly) extends java.lang.Comparable[Int].

My question is why doesn't it extends java.lang.Comparable[RichInt]?

The reason that I raise this question is in Java, I would write code like this:

class A implements Comparable<A> {

    @Override

    public int compareTo(A other) {
        //implement the method.
    }
    ....
}
like image 652
CodingNow Avatar asked Dec 19 '25 09:12

CodingNow


1 Answers

Firstly we need to know RichInt is used for supplying helper functions for Int type by implicit conversions defined in the Predef:

@inline implicit def intWrapper(x: Int) = new runtime.RichInt(x)

So you can use it like:

2.doubleValue()
2.shortValue()
...

And for your question: why doesn't it extends java.lang.Comparable[RichInt]

Because we actually is operating on the Int type, not the RichInt type. like:

2.compare(3)
like image 152
chengpohi Avatar answered Dec 21 '25 05:12

chengpohi