Saturday 20 June 2009

Functions passed to functions (delegates)


def turnNumbersToEven() = {
val nums = 1 to 20
println( nums.map(a => addOneToNumberIf(a % 2 == 1)( a)) )
}
def addOneToNumberIf( test : => Boolean)( i : Int) : Int = {
if (test) {
return i + 1
} else {
return i
}
}


Note because we used addOneToNumberIf(a)(b) notation instead of addOneToNumberIf(a,b) notation we are allowed to write scripts {} like this:


def turnNumbersToEven() = {
val nums = 1 to 20
println( nums.map(a => addOneToNumberIf {a % 2 == 1} (a)) )
}

No comments:

Post a Comment