高阶函数
高阶函数可以将其他函数作为参数或者使用函数作为输出结果
//函数作为参数
def doSquare(f:Int=>Int,p:Int)=f(p)
def square(x:Int):Int=x*x
doSquare(square,square(2))
//函数作为返回值
//返回类型为函数(Int=>Int)
def doSquare()={
(x:Int)=>x*x
}
doSquare()(2)
常用高阶函数
- map
- foreach
- filter
- fold、foldLeft、foldRight
- reduce
- zip
- flatten
- flatMap
函数作为参数
object test {
def main(args: Array[String]): Unit = {
def fun1(a:Int,b:Int):Int=a+b
def fun2(a:Int,b:Int):Int=a-b
def fun3(a:Int,b:Int):Int=a*b
def fun4(a:Int,b:Int):Int=a/b
def funTest(f:(Int,Int)=>Int,a:String):String={
val resultValue=f(10,5)
a+resultValue
}
var str=funTest(fun1,"你的价格是:")
println(str)
}
}