def sum(a:Int, b:Int):Int= a + b
val ab:(Int,Int)=>Int=(a:Int, b:Int)=> a + b
val ba = ab
println(sum(2,3))println(ab(2,3))println(ba(2,3))
练习
val a:String="aaa"
val b:Int=20
val c:(Int,Int)=>Int=(a, b)=> a + b
val d:(Int,Int)=>Int= c
函数作为参数传递
def funTest(f:(Int,Int)=>Int, msg:String):String={
val a =100
val b =50
msg +f(a, b)}println(funTest((a:Int, b:Int)=> a + b,"和为"))println(funTest((a, b)=> a * b,"积为"))
练习1
def funTest2():(String,String)=>String={
def funDemo2(a:String, b:String):String={
a + b
}funDemo2(a, b)=> a + b
}println(funTest2()("张三","牛"))
def ma():Int=>(Int,Int)=>Int={
a =>{if(a %2==1){(a, b)=> a + b
}else{(a, b)=> a - b
}}}println(ma()(2)(2,3))
练习2
//传两个数字num1 num2
def ma2(num1:Int, num2:Int, f:(Int,Int)=>Int):(Int,Int)=>Int={if(f(num1, num2)%2==0){(a, b)=> a + b
}else{(a, b)=> a - b
}}println(ma2(10,20,(a, b)=> a + b)(99,98))
命名方法def 方法名(参数名:参数类型[泛型]):返回类型={方法体}取两值中的最小值def minValue(a: Int, b: Int): Int = { if (a > b) b else a}val i = minValue(2, 3)println(i)def myName(name: String, age: Int): String = { s"我的名字是$name,我的年龄是$age"}println(myName("张三", 20))