函数作为值传递
scala> def fun1(field: String,field1: String) = println(s"fun1 field = $field, field1 = $field1")
fun1: (field: String, field1: String)Unit
scala> def fun2 = fun1 _
fun2: (String, String) => Unit
scala> fun2("info1","info2")
fun1 field = info1, field1 = info2
匿名函数
scala> def fun3 = (i: Int, j: Int) => println(s"i = $i, j = $j")
fun3: (Int, Int) => Unit
scala> fun3(1,2)
i = 1, j = 2
高阶函数 (参数为函数的函数)
// 方法名: (参数类型,参数类型) => 返回值类型
scala> def fun4(name: String, func: (String, String) => Unit): Unit = func(name,name+"1")
fun4: (name: String, func: (String, String) => Unit)Unit
// (字段名: 类型, 字段名: 类型) => 函数体
scala> fun4("abc",(field1: String,field2: String) => println(s"field1 = $field1, field2 = $field2"))
field1 = abc, field2 = abc1
参数
// 无参数
scala> def fun(f: () => Unit) = f
fun: (f: () => Unit)() => Unit
// 一个参数
scala> def fun(f: String => Unit) = f
fun: (f: String => Unit)String => Unit
实例
// 返回的是一个值域
scala> 1 to 10
res6: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// 包含一个值域的类型的数组
scala> Array(1 to 10)
res8: Array[scala.collection.immutable.Range.Inclusive] = Array(Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
// 取出值域的每一个元素放入数组
scala> val arr = Array(1 to 10:_*)
arr: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// 传入函数对每一元素应用函数,取返回值组成一个新的数组
scala> arr.map((x: Int) => x + 1)
res10: Array[Int] = Array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
// 自动类型推断
scala> arr.map(x => x + 1)
res11: Array[Int] = Array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
// 使用占位符 _ 代表每一个元素
scala> arr.map(_ + 1)
res12: Array[Int] = Array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
闭包
函数的变量不在其作用域内被调用,就是闭包的概念
def funOut(): Unit ={
val num = 10
def funIn(): Unit ={
// funIn 直接访问外面的 num变量
println(num)
}
funIn()
}
柯理化
def main(args: Array[String]): Unit = {
// fun1 和 fun2 等价
fun1(1,2)
fun2(1)(2)
}
// 传入2个参数
def fun1(x: Int, y: Int): Unit ={
println(s"x = $x, y = $y")
}
// 将参数转换为函数
def fun2(x: Int) = (y: Int) => println(s"x = $x, y = $y")