偏函数:当函数有多个参数,而在使用该函数时不想提供所有参数(比如函数有3个参数),只提供0~2个参数,此时得到的函数便是偏函数。
object PartialAppliedFunction {
def main(args: Array[String]): Unit = {
def sum(a:Int,b:Int,c:Int) = a+ b+c
println(sum(1,2,3))
val fa = sum _ //偏函数
println(fa(2,3,4))
println(fa.apply(3, 3, 4))
val fb = sum(1,2,_:Int) //偏函数
println(fb(6))
val data = List(1,2,3,4,5,6)
data.foreach (println _)
data.foreach(x =>println(x))
data.foreach(println)
}
}
闭包:
object ClosureTest {
def main(args: Array[String]): Unit = {
//more是一个自由变量,其值及类型是在运行的时候得以确定的
//x是类型确定的,其值是在函数调用的时候被赋值的
//这样的函数称之为闭包:从开放到封闭的过程
def add(more:Int) = (x:Int) => x+ more
//给more赋值
val add1 = add(1)
//调用add函数
println(add1(100))
}
}