为什么Int不从Ordered [Int]继承/扩展 [英] Why does Int not inherit/extend from Ordered[Int]

查看:83
本文介绍了为什么Int不从Ordered [Int]继承/扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对字体设计有疑问.为什么Int不扩展Ordered特性. Int不是按天性排序的吗?

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

相反,scala库提供了隐式的"orderer"方法,这些方法将Int转换为Ordered [Int].在这里有哪些设计选择?

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

摘自《 Scala编程》一书的示例

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

推荐答案

因为Int(以及从AnyVal继承的其他一些类)是短暂的-在运行时,它通常由不具有类概念的原始值表示(因此继承) ).当然,也有例外,例如将项放入集合时将Int装箱到完整的引用类实例,但typeclass提供了一种通用解决方案.此外,类型类比继承比继承更灵活.

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.

这篇关于为什么Int不从Ordered [Int]继承/扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆