English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The syntax for defining anonymous functions in Scala is very simple, with the arrow on the left being the parameter list and the right being the function body.
After using the anonymous function, our code becomes more concise.
The following expression defines an anonymous function that accepts an Int type input parameter:
var inc = (x:Int) => x+1
The anonymous function defined above is actually a shorthand for the following style:
def add2 = new Function1[Int,Int]{ def apply(x:Int):Int = x+1; }
The inc in the above example can now be used as a function, as follows:
var x = inc(7)-1
Similarly, we can define multiple parameters in anonymous functions:
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 define anonymous functions without parameters, as shown below:
var userDir = () => { System.getProperty("user.dir") }
userDir can now be used as a function, as follows:
println( userDir() )
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
}
Keep the above code in the Demo.scala file and execute the following command:
$ scalac Demo.scala $ scala Demo
The output result is:
multiplier(1) value = 3 multiplier(2) value = 6