Scala Anonymous Functions

Advertisements


Scala provides a relatively lightweight syntax for defining anonymous functions. Anonymous functions in source code are called function literals and at run time, function literals are instantiated into objects called function values.

Scala supports first-class functions, which means you can express functions in function literal syntax, i.e., (x: Int) => x + 1, and that functions can be represented by objects, which are called function values. The following expression creates a successor function for integers:

var inc = (x:Int) => x+1

Variable inc is now a function that can be used the usual way:

var x = inc(7)-1

It is also possible to define functions with multiple parameters as follows:

var mul = (x: Int, y: Int) => x*y

Variable mul is now a function that can be used the usual way:

println(mul(3, 4))

It is also possible to define functions with no parameter as follows:

var userDir = () => { System.getProperty("user.dir") }

Variable userDir is now a function that can be used the usual way:

println( userDir )


Advertisements
Advertisements