上接:scala教程:lambda表达式
至简原则
- 参数的类型可以省略,会根据形参进行自动的推导
- 只有一个参数,小括号可以 省略;但没有参数 或 参数数量超过 1,不能省略小括号
- 函数体只有一行,则花括号可以省略
- 在函数体中 只出现一次形参,可省略形参,在函数内使用
_ 表示形参 - 如果可以推断出,传入的
println(_) 是函数体,可只保留 println
完整写法
//定义函数,其形参是一个函数
def test(fun:String => Unit) : Unit={
fun("测试")
}
//定义另一个函数
def say(str:String): Unit ={
println(str)
}
//调用test()函数,并将 say()函数作为参数传入test()
test(say)
lambda表达式
//定义函数,其形参是一个函数
def test(fun:String => Unit) : Unit={
fun("测试test")
}
//调用test()函数,传入lambda表达式
test((str:String) =>{
println(str)
})
原则1
def main(args: Array[String]): Unit = {
def test(fun:String => Unit) : Unit={
fun("测试")
}
test((s) => {
println(s)
})
}
原则2
def main(args: Array[String]): Unit = {
def test(fun:String => Unit) : Unit={
fun("测试")
}
test(s => {
println(s)
})
}
原则3
def main(args: Array[String]): Unit = {
def test(fun:String => Unit) : Unit={
fun("测试")
}
test(s => println(s) )
}
原则4
def main(args: Array[String]): Unit = {
def test(fun:String => Unit) : Unit={
fun("测试")
}
test( println(_) )
}
4.1
def main(args: Array[String]): Unit = {
def test2( fun: (Int,Int)=>Int ):Int ={
fun(1,2)
}
def fun2(s:Int,s2:Int) ={
s+s2
}
println( test2( fun2(_,_) ) )
}

原则5
def main(args: Array[String]): Unit = {
def test(fun:String => Unit) : Unit={
fun("测试")
}
test( println )
}
原文出处:/show_1IX1BQpad7Rq.html