Easy Tutorial
❮ Scala For Loop Scala Options ❯

Scala Anonymous Functions

Scala Functions

The syntax for defining anonymous functions in Scala is straightforward, with the parameter list on the left side of the arrow and the function body on the right.

Using anonymous functions makes our code more concise.

The following expression defines an anonymous function that accepts an Int type input argument:

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

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

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

The inc defined 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 define an anonymous function without 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 into a file named Demo.scala, and execute the following commands:

$ scalac Demo.scala
$ scala Demo

The output will be:

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

Scala Functions

❮ Scala For Loop Scala Options ❯