Scala 2.8 TreeMap 和自定义排序 [英] Scala 2.8 TreeMap and custom Ordering
问题描述
我正在从 Scala 2.7 切换并订购到 Scala 2.8 并使用订购.它看起来很简单,但我想知道我能不能让它不那么冗长.例如:
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
如果我尝试创建一个 TreeMap,我会收到一个错误
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]()
^
但是,如果我明确指定对象 A 作为排序,它工作正常.
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?
谢谢
推荐答案
请注意诊断中的隐式"一词.参数声明为 implicit
意味着编译器将尝试在您调用构造函数时在作用域中找到合适的值.如果您将 Ordering 设为隐式值,则编译器将对其进行这种处理:
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:
scala> implicit object A extends Ordering[A] { def compare(o1: A, o2: A) = o1.i - o2.i}
defined module A
scala> val tm1 = new collection.immutable.TreeMap[A, String]()
tm1: scala.collection.immutable.TreeMap[A,String] = Map()
该示例在 REPL 中有效,因为 REPL 将您的代码包含在不可见的类定义中.这是一个独立工作的:
That example works in the REPL because the REPL encloses your code in invisible class definitions. Here's one that works free-standing:
case class A(val i:Int) extends Ordered[A] { def compare(o:A) = i - o.i }
object A { implicit object AOrdering extends Ordering[A] { def compare(o1: A, o2: A) = o1.i - o2.i } }
class B {
import A.AOrdering
val tm1 = new collection.immutable.TreeMap[A, String]()
}
这篇关于Scala 2.8 TreeMap 和自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!