Scala anonymous function


Release date:2023-11-17 Update date:2023-11-17 Editor:admin View counts:141

Label:

Scala anonymous function

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

After using anonymous functions, our code becomes more concise.

The following expression defines an acceptance of a Int anonymous function for type input parameters:

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

The anonymous function defined above is actually an abbreviation of the following:

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

For the above example inc 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 not set parameters for anonymous functions, 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
}

Keep the above code to Demo.scala file, execute the following command:

$ scalac Demo.scala
$ scala Demo

The output is as follows:

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

Powered by TorCMS (https://github.com/bukun/TorCMS).