定义一个参数是函数的函数。(完整定义=>匿名函数)
object helloWorld {
def main(args: Array[String]): Unit = {
def addxy(x:Int, y:Int):Int=x+y
def mulxy(x:Int, y:Int):Int=x*y
def func1(a:Int, b:Int, f:(Int, Int)=>Int):Int={f(a,b)}
val res1 = func1(1, 2, addxy)
val res11 = func1(1, 2, (x:Int, y:Int) => x+y)
val res2 = func1(1, 2, mulxy)
val res22 = func1(1, 2, (x:Int, y:Int) => x*y)
println(res1, res11)
println(res2, res22)
// println("hello world")
}
}
可以看到res1和res11的含义是一样的。
我们可以将匿名函数的参数简化:(缺省类型)
object helloWorld {
def main(args: Array[String]): Unit = {
def addxy(x:Int, y:Int):Int=x+y
def mulxy(x:Int, y:Int):Int=x*y
def func1(a:Int, b:Int, f:(Int, Int)=>Int):Int={f(a,b)}
val res1 = func1(1, 2, addxy)
val res11 = func1(1, 2, (x, y) => x+y)
val res2 = func1(1, 2, mulxy)
val res22 = func1(1, 2, (x, y) => x*y)
println(res1, res11)
println(res2, res22)
// println("hello world")
}
}
更进一步
将匿名函数的参数用通配符进行简化:
object helloWorld {
def main(args: Array[String]): Unit = {
def addxy(x:Int, y:Int):Int=x+y
def mulxy(x:Int, y:Int):Int=x*y
def func1(a:Int, b:Int, f:(Int, Int)=>Int):Int={f(a,b)}
val res1 = func1(1, 2, addxy)
val res11 = func1(1, 2, _+_)
val res2 = func1(1, 2, mulxy)
val res22 = func1(1, 2, _*_)
println(res1, res11)
println(res2, res22)
// println("hello world")
}
}
用老师的话来说,化简到没学过就看不懂的地步就到位了。确实,没学过确实看不懂_+_原来就是x+y这么个函数的意思。
完整定义:
object helloWorld {
def main(args: Array[String]): Unit = {
def addxy(x:Int, y:Int):Int=x+y
def mulxy(x:Int, y:Int):Int=x*y
def func2(a:Int):(Int, Int) => Int = {
if(a > 0) addxy
else mulxy
}
println("fun2")
println(func2(1)(1, 2))
println(func2(-1)(1, 2))
}
}
进行简化(使用通配符):
object helloWorld {
def main(args: Array[String]): Unit = {
def func1(a:Int, b:Int, f:(Int, Int)=>Int):Int={f(a,b)}
def func2(a:Int):(Int, Int) => Int = {
if(a > 0) _+_
else _*_
}
println("fun2")
println(func2(1)(1, 2))
println(func2(-1)(1, 2))
}
}
记录一下,以防以后忘记这新奇玩意。
老师课上的内容