Thursday, December 10, 2009

Scala functions as data

Here is a short example showing functions being treated as data and then their execution. Note: this example contains global data and side-effects, not the proper way to write functional code. The point is to show the functions (i.e., a, b and c) being held in a list as data.

var x = 1

def a() {x = x * 2}
def b() {x = x * 3}
def c() {x = x * 5}

val fns = List[() => Unit](a, b, c)

println(x) // prints 1
println(x) // prints 30

Calling fns.foreach cycles though the list of functions, executing each one.