Scala 2.8 TreeMap 和自定义排序
我正在从 scala 2.7 切换到 scala 2.8 并使用排序。它看起来很简单,但我想知道我能否让它变得不那么冗长。例如:
scala> case class A(i: Int)
defined class A
scala> object A extends Ordering[A] { def compare(o1: A, o2: A) = o1.i - o2.i}
defined module A
如果我随后尝试创建一个 TreeMap,则会收到错误
scala> new collection.immutable.TreeMap[A, String]()
<console>:10: error: could not find implicit value for parameter ordering: Ordering[A]
new collection.immutable.TreeMap[A, String]()
^
但是,如果我显式指定对象 A 作为顺序,则它可以正常工作。
scala> new collection.immutable.TreeMap[A, String]()(A)
res34: scala.collection.immutable.TreeMap[A,String] = Map()
我是否总是必须明确指定顺序或者是否有更短的格式?
谢谢
I'm switching from scala 2.7 and ordered to scala 2.8 and using ordering. It looks quite straight forward but I was wondering could I make it a little less verbose. For example:
scala> case class A(i: Int)
defined class A
scala> object A extends Ordering[A] { def compare(o1: A, o2: A) = o1.i - o2.i}
defined module A
If I then try to create a TreeMap I get an error
scala> new collection.immutable.TreeMap[A, String]()
<console>:10: error: could not find implicit value for parameter ordering: Ordering[A]
new collection.immutable.TreeMap[A, String]()
^
However if I explicitly specify the object A as the ordering it works fine.
scala> new collection.immutable.TreeMap[A, String]()(A)
res34: scala.collection.immutable.TreeMap[A,String] = Map()
Do I always have to explicitly specify the ordering or is there a shorter format?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请注意,有一种稍微不那么冗长的创建
Ordering
的方法:Ordering 的主要优点是您可以为同一个类提供许多排序。如果您的
A
类确实是Ordered
,那么您应该扩展它。如果没有,您可以显式传递 Ordering,而不是使用隐式:Mind you, there's a slightly less verbose way of creating an
Ordering
:The main advantage of Ordering being you can provide many of them for the same class. If your
A
class is trulyOrdered
, then you should just extend that. If not, instead of using implicits, you may pass an Ordering explicitly:请注意诊断中的“隐式”一词。该参数被声明为
隐式
,这意味着编译器将在您调用构造函数时尝试在范围内找到合适的值。如果您将 Ordering 设置为隐式值,则编译器将有资格进行这种处理:编辑:
该示例在 REPL 中有效,因为 REPL 将您的代码包含在不可见的类定义中。这是一个独立工作的:
Notice the word "implicit" in the diagnostic. The parameter is declared
implicit
meaning the compiler will try to find a suitable value in scope at the point you invoke the constructor. If you make your Ordering an implicit value, it will be eligible for this treatment by the compiler:Edit:
That example works in the REPL because the REPL encloses your code in invisible class definitions. Here's one that works free-standing:
不要扩展
Ordering[A]
,而是尝试扩展Ordered[A]
。就像这样:Instead of extending
Ordering[A]
, try extendingOrdered[A]
. Like so: