【问题标题】:Why does Int not inherit/extend from Ordered[Int]为什么 Int 不从 Ordered[Int] 继承/扩展
【发布时间】:2013-04-06 17:32:39
【问题描述】:

我有一个关于字体设计的问题。为什么 Int 不扩展 Ordered 特征。 Int 不是自然排序的吗?

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

示例取自《Scala 编程》一书

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


maxListImpParm(List(1,5,10,3)) // works because of implicit methods

【问题讨论】:

  • 声明可简写为:def maxListImpParm[T &lt;% Ordered[T]](elements:List[T]):T = ???

标签: scala implicit-conversion implicit


【解决方案1】:

因为 Int(以及从 AnyVal 继承的一些其他类)是短暂的——在运行时它通常由根本没有类(因此继承)概念的原始值表示。当然,也有例外,例如当您将项目放入集合时,对完整的引用类实例进行 Int 装箱,但 typeclass 提供了一种通用解决方案。此外,类型类是more flexible than inheritance。

【讨论】:

  • 自从回答了这个问题value classes 被添加到语言中。是否可以使用值类对 Int 进行改造,以便从 Ordered[Int] 扩展?
猜你喜欢
  • 2013-07-21
  • 2015-08-19
  • 2019-09-20
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多