Scala高阶函数示例

时间:2021-08-11 16:38:44

object Closure {

    def function1(n: Int): Int = {
val multiplier = (i: Int, m: Int) => i * m
multiplier.apply(n, 2)
} def function2(m: Int => Int) = m def function3(f: (Int, Int) => Int) = f val function4 = (x: Int) => x + 1 val function5 = (x:Int) => {
if(x > 1){
//...
}else{
//...
}
} val function6 = (_ : Int) + ( _ :Int) def function7(a:Int, b:Int, c:Int) = a+b+c val function8 = function7 _ val function9 = function7(1, _:Int, 3) def function10(x:Int) = (y:Int) => x+y def function11(args: Int*) = for (arg <- args) println(arg) def function12(x: Int): Int = {
if (x == 0) {
throw new Exception("bang!")
}
else{
function12(x -1)
}
} def hello1(m: Int): Int = m def hello2(m: Int, n: Int): Int = m * n def main(args: Array[String]) {
println(function1(2))
println(function2(hello1)(2))
println(function3(hello2)(2, 3))
println(function4(4))
println(function4(5))
function6(1, 2)
function8(1, 2, 3)
function8.apply(1, 2, 3)
function9.apply(1)
function10(1)(2)
function11(1, 2, 3, 4)
function11(Array(1, 2, 3): _*)
} }