6

I have a question on type design. Why does Int not extend the Ordered trait. Isn't Int ordered by nature?

Instead, the scala library provides implicit 'orderer' methods which convert Int to Ordered[Int]. What are the design choices being made here?

Example taken from the book Programming in Scala

def maxListImpParm[T <% Ordered[T]](elements:List[T]):T= ...


maxListImpParm(List(1,5,10,3)) // works because of implicit methods
RAbraham
  • 5,956
  • 8
  • 45
  • 80

1 Answers1

9

Because Int (and some other classes inherited from AnyVal) is ephemeral -- at runtime it usually represented by primitive value which has no notion of class (and thus inheritance) at all. Of course, there are exceptions, like Int boxing to full blown reference class instance when you put item in collection, but typeclass provides one universal solution. Moreover, typeclasses are more flexible than inheritance.

Community
  • 1
  • 1
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
  • Since this question was answered [value classes](https://docs.scala-lang.org/overviews/core/value-classes.html) were added to the language. Could `Int` have been retrofitted, using value classes, in order to extend from `Ordered[Int]`? – Paul Carey May 31 '21 at 08:54