import scala.collection._
val m = CustomizedSortedMap(20150401 -> "A", 20150423 -> "B")
println(m.get(20150402)) // expected "A"
println(m.get(20150422)) // expected "A"
println(m.get(20150423)) // expected "B"
println(m.get(20150424)) // expected "B"
如何在scala中实现这样的Customized SortedMap?欢迎任何示例或代码片段!谢谢!
答案 0 :(得分:2)
通过使用TreeMap
(有序地图)的隐式转换,您可以轻松实现这样的方法:
implicit class CustomizedSortedMap[A, +B](treeMap: TreeMap[A, B]) {
def getLatest(a: A): Option[B] = {
treeMap.to(a).lastOption.map(_._2)
}
}
val m = TreeMap(20150401 -> "A", 20150423 -> "B")
println(m.getLatest(20150402)) // prints "Some(A)"
println(m.getLatest(20150422)) // prints "Some(A)"
println(m.getLatest(20150423)) // prints "Some(B)"
println(m.getLatest(20150424)) // prints "Some(B)"