Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Int not inherit/extend from Ordered[Int]

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
like image 687
RAbraham Avatar asked Apr 14 '13 15:04

RAbraham


1 Answers

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.

like image 85
om-nom-nom Avatar answered Sep 19 '22 12:09

om-nom-nom