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

孤者浪人 提交于 2020-01-03 10:44:53

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/16001010/why-does-int-not-inherit-extend-from-orderedint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!