介绍
Methods may define multiple parameter lists. When a method is called with a fewer number of parameter lists, then this will yield a function taking the missing parameter lists as its arguments.
定义的一个函数有多个参数,如果只传入了其中部分参数,那么它就变成了另一个函数,参数列表是,之前缺少的参数。
举例
object CurryTest extends App {
def filter(xs: List[Int], p: Int => Boolean): List[Int] =
if (xs.isEmpty) xs
else if (p(xs.head)) xs.head :: filter(xs.tail, p)
else filter(xs.tail, p)
def modN(n: Int)(x: Int) = ((x % n) == 0)
val nums = List(1, 2, 3, 4, 5, 6, 7, 8)
println(filter(nums, modN(2)))
println(filter(nums, modN(3)))
}
如上所示,modN需要两个参数,返回值是一个boolean型的;如最后两行所示,如果只传了一个参数,那么这个函数就变成了需要一个参数,返回boolean值。
刚好符合filter的第二个参数的定义,入参是Int,结果是Boolean。
网友评论