一、函数值
在Scala里,可以在函数里创建函数,将函数赋给引用,或者把它们当做参数传给其他函数。
示例1:
def totalResultOverRange(number:Int, codeBlok:Int => Int) : Int = {
var result = 0
for(i <- 1 to number){
result += codeBlok(i)
}
result
}
调用方法1:
var result = totalResultOverRange(10, i => (if(i % 2 == 0) i else 0))
println("result:"+ result)
调用方法2:
// 先定义一个函数值
def codeFunc(i: Int): Int = {
if(i % 2 == 0) i else 0
}
var result = totalResultOverRange(10, codeFunc)println("result:"+ result)
上面两种调用方法,结果为:
result:30
多参数示例:
def inject(arr: Array[Int], initial:Int, operation:(Int, Int) => Int) = {
var carryOver = initial
arr.foreach(i => carryOver = operation(carryOver, i))
carryOver
}
调用1:
val array = Array(2,3,5,1,6,4)结果1:
val sum = inject(array, 0, (carryOver,elem) => carryOver + elem)
println("Sum of elements in array is " + sum )
Sum of elements in array is 21
调用2:
val array = Array(2,3,5,1,6,4)
val sum = inject(array, 0, (carryOver,elem) => Math.max(carryOver, elem))
println("Max of elements in array is " + sum )
结果2:
Max of elements in array is 6
二、Curry化
Scala里的Curry化可以把函数从接收多个参数转换成多个参数列表。如果要用同样的一组实参多次调用一个函数,可以用curry化来减少噪音,让代码更有味道。
我们来看看Scala如何提供curry化的支持。我们要编写的方法不是接收一个参数列表,里面有多个参数,而是有多个参数列表,每个里面可以有一个或多个参数。
也就是说,写的不是def foo(a: Int, b: Int, c: Int){},而是 def foo(a: Int)(b: Int)(c: Int){}。可以这样调用这个方法,比如:foo(1)(2)(3)、foo(1){2}{3},甚至这样foo{1}{2}{3}。
示例:
def cusFoldLeft(arr:Array[Int], initial:Int)(operation:(Int,Int) => Int) = {
var carryOver = initial
arr.foreach(e => carryOver = operation(carryOver, e))
carryOver
}
调用:
val array = Array(2,3,5,1,6,4)
val max = cusFoldLeft(array, 0){
(carryOver, elem) => Math.max(carryOver, elem)
}
println("max:"+max)
结果:
max:6