你需要传递函数签名f: (Map[String,List[(String, Double)]], String) => Double
而不仅仅是返回类型。下方的轻视例如:
var testMap: Map[String, List[(String, Double)]] = Map(
"First" -> List(("a", 1.0), ("b", 2.0)),
"Second" -> List(("c", 3.0), ("d", 4.0))
)
// testMap: Map[String,List[(String, Double)]] = Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
def doSomeComputation(m1: Map[String, List[(String, Double)]], name: String): Double = {
m1.getOrElse(name, List[(String, Double)]()).map(x => x._2).max
}
// doSomeComputation: (m1: Map[String,List[(String, Double)]], name: String)Double
def doSomeOtherComputation(m1: Map[String, List[(String, Double)]], name: String): Double = {
m1.getOrElse(name, List[(String, Double)]()).map(x => x._2).min
}
// doSomeOtherComputation: (m1: Map[String,List[(String, Double)]], name: String)Double
def otherFunction(f: (Map[String, List[(String, Double)]], String) => Double, otherName: String) = {
f(testMap, "First") * otherName.length
}
// otherFunction: (f: (Map[String,List[(String, Double)]], String) => Double, otherName: String)Double
println(otherFunction(doSomeComputation, "computeOne"))
// 20.0
println(otherFunction(doSomeOtherComputation, "computeOne"))
// 10.0
根据您的使用情况下,它可能是一个好主意,还通过testMap
和name
作为参数传递给otherFunction
。
这不是传递函数作为参数,而是传递函数的结果。 –
是的,你是对的 – MLeiria