你需要傳遞函數簽名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