函数和方法
函数和方法的入参都是val的,不可变的,并且需要给出参数类型
将一个方法赋值给一个变量需要在方法名后面加上 空格+"_"
def func() = {
}
val a = func _
object FunctionTest {
def main(args: Array[String]): Unit = {
println("----------1. basic----------")
def func01(): Unit = {
println("hello world")
}
println(func01())
println("----------2. 递归方法----------")
def func02(num: Int): Int = {
if (num == 1) {
num
} else {
num * func02(num - 1)
}
}
println(func02(4))
println("----------3. 方法参数的默认值----------")
def func03(a: Int = 8, b: String = "abc") = {
println(s"$a $b")
}
func03()
func03(10)
func03(b = "888")
println("----------4. 匿名函数----------")
val plus = (a: Int, b: Int) => {
a + b
}
println(plus(2, 9))
println("----------5. 嵌套方法----------")
def func05(a: String) = {
def func01() = {
println(a)
}
func01()
}
func05("hello 嵌套函数")
println("----------6. 偏应用方法----------")
def func06(date: Date, tp: String, msg: String) = {
println(s"$date $tp $msg")
}
val info = func06(_: Date, "info", _: String)
info(new Date(), "info...")
val error = func06(_:Date, "error", _: String)
error(new Date(), "error...")
println("----------7. 方法的可变参数----------")
def func07(a: Int*): Unit = {
a.foreach(println)
}
func07(1, 2, 3, 4, 5)
println("----------8. 高阶函数----------")
def compute(a: Int, b: Int, f: (Int, Int) => Int) = {
f(a, b)
}
println(compute(1, 3, (x: Int, y: Int) => {x + y}))
println(compute(1, 3, _ + _))
def factory(computeSign: String): (Int, Int) => Int = {
if (computeSign.equals("+")) {
(x: Int, y: Int) => x + y
} else if (computeSign.equals("-")) {
(x: Int, y: Int) => x - y
} else if (computeSign.equals("*")) {
(x: Int, y: Int) => x * y
} else {
(x: Int, y: Int) => x / y
}
}
println(s"1 + 2 = ${compute(1, 2, factory("+"))}")
println(s"1 - 2 = ${compute(1, 2, factory("-"))}")
println(s"1 * 2 = ${compute(1, 2, factory("*"))}")
println(s"1 / 2 = ${compute(1, 2, factory("/"))}")
println("----------9. 柯里化----------")
def func09(a: Int*)(b: String*) = {
a.foreach(println)
b.foreach(println)
}
func09(1, 2, 3, 4)("apple", "banana")
}
}
打印结果
----------2. 递归方法----------
24
----------3. 方法参数的默认值----------
8 abc
10 abc
8 888
----------4. 匿名函数----------
11
----------5. 嵌套方法----------
hello 嵌套函数
----------6. 偏应用方法----------
Sat Nov 06 16:43:46 CST 2021 info info...
Sat Nov 06 16:43:46 CST 2021 error error...
----------7. 方法的可变参数----------
1
2
3
4
5
----------8. 高阶函数----------
4
4
1 + 2 = 3
1 - 2 = -1
1 * 2 = 2
1 / 2 = 0
----------9. 柯里化----------
1
2
3
4
apple
banana
Process finished with exit code 0