我有一个Map[String, Any]
甜甜圈
val donuts: Seq[Map[String, Any]] = Seq(Map("type" -> "plain", "price" -> 1.5), Map("type" -> "jelly", "price" -> 2.5))
我希望使用maxBy
找到价格最高的甜甜圈。
val d = donuts.maxBy(donut => donut("price").toString.toDouble)
成功返回Map[String,Any] = Map(type -> "jelly", price -> 2.5)
我可以访问d("price")
来查找价格最高的甜甜圈的价格。但如果我尝试在一行中这样做:
donuts.maxBy(donut => donut("price").toString.toDouble)("price")
它扔了:
error: type mismatch; found : String("price") required: Ordering[Double] (donuts.maxBy(donut => donut("price").toString.toDouble))("price") ^
这里的问题是什么,如何将其推广到一行?
答案 0 :(得分:3)
那是因为maxBy
需要隐式排序参数:
def maxBy[B](f: A => B)(implicit cmp: Ordering[B]): A
不幸的是,你不能使用apply的语法糖,因为你作为第二个参数列表传递的任何内容都将被传递,就像它是隐式参数一样。 您可以通过以下方式明确调用apply:
donuts.maxBy(donut => donut("price").toString.toDouble).apply("price")
它并不像你正在寻找的那样漂亮,但它仍然只是一个班轮。
希望有所帮助:)