高阶函数(就是可以接收一个函数作为参数的函数)

带参高阶函数示例

1
2
3
4
5
6
7
8
9
10
11
12
13
	object HigherFunction {
def main(args: Array[String]): Unit = {
println(test(sum, 100))
}

def test(f: Double => Double, n1: Double) = {
f(n1)
}

def sum(d: Double): Double = {
d + d
}
}

无参高阶函数示例

1
2
3
4
5
6
7
8
9
10
11
12
13
object HigherFunction02 {
def main(args: Array[String]): Unit = {
test(sayHello)
}

def test(f1PrintHello: () => Unit) = {
f1PrintHello()
}

def sayHello(): Unit = {
println("helloaaa")
}
}

高阶函数底层调用原理

在jvm有三个核心的底层区块 (栈、堆、方法区块)

  • 当我们在加载过程中,这两个函数就会被加载进去
1
2
3
4
5
6
7
def test(f: Double => Double, n1: Double) = {
f(n1)
}

def sum(d: Double): Double = {
d + d
}
  • 当我们区调用test(sum, 100)这个函数的时候,会在栈区开辟一个空间,我们也会进入到test函数中去,另开辟一个空间,当我们调用test(sum, 100)的时候就相当于会把f函数的地址指向给test(sum, 100)这个函数,所以在执行f函数的时候就相当于调用sum这个函数

高阶函数进阶

嵌套多个函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.sky.scala.exercise17

object HigherOrderFunction {
def main(args: Array[String]): Unit = {
// 高阶函数可以嵌套多个函数
def test(f1: Double => Double, d: Double): Double = {
f1(mod(d))
}

def sum(d: Double): Double = {
d + d
}

def mod(d2: Double): Double = {
d2 % 2
}

println(test(sum, 100))
}
}

高阶函数返回函数类型

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.sky.scala.exercise17

object HigherOrderFunction2 {
def main(args: Array[String]): Unit = {

def minus(n: Int) = {
(y: Int) => n - y
}

// 函数作为返回值执行方式一
val f1 = minus(10)
println(f1(20))
// 函数作为防护之执行方式二
// 函数柯里化
println(minus(10)(30))

}
}