Scala Anonymous Functions
Defining an anonymous function in Scala is simple: the left side of the arrow is the parameter list, and the right side is the function body.
After using anonymous functions, our code becomes more concise.
The following expression defines an anonymous function that takes one input parameter of type Int:
var inc = (x:Int) => x+1
The anonymous function defined above is actually shorthand for the following form:
def add2 = new Function1[Int,Int]{
def apply(x:Int):Int = x+1;
}
The inc in the example above can now be used as a function, as follows:
var x = inc(7)-1
Similarly, we can define multiple parameters in an anonymous function:
var mul = (x: Int, y: Int) => x*y
mul can now be used as a function, as follows:
println(mul(3, 4))
We can also give the anonymous function no parameters, as shown below:
var userDir = () => { System.getProperty("user.dir") }
userDir can now be used as a function, as follows:
println( userDir() )
Example
Example
object
Demo
{
def
main
(
args
:
Array
[
String
]
)
{
println
(
"multiplier(1) value = "
- multiplier
(
1
)
)
println
(
"multiplier(2) value = "
- multiplier
(
2
)
)
}
var
factor
=
3
val
multiplier
=
(
i
:
Int
)
=>
i
factor
}
Save the above code to a Demo.scala file and run the following command:
$ scalac Demo.scala
$ scala Demo
The output is:
multiplier(1) value = 3
multiplier(2) value = 6
Scala Functions