Scala Anonymous Functions

Scala 函数Scala Functions

The syntax for 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 accepts an Int type input parameter:

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

The anonymous function defined above is actually shorthand for the following syntax:

def add2 = new Function1[Int,Int]{  
    def apply(x:Int):Int = x+1;  
} 

The inc from the above example 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 set no parameters for an anonymous function, 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 execute the following commands:

$ scalac Demo.scala
$ scala Demo

The output is:

multiplier(1) value = 3
multiplier(2) value = 6

Scala 函数Scala Functions

Other Extensions