Latest web development tutorials

Scala anonymous functions

Scala function Scala function

Scala anonymous functions defined in the syntax is very simple, the arrow on the left is the parameter list, the right is the body of the function, the type parameter is omitted, Scala's type inference will infer type arguments. After the use of anonymous functions, our code more concise.

The following expression defines a accepts an input parameter of type Int anonymous function:

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

Anonymous function defined above, in fact, such an approach is shorthand for the following:

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

inc above example can now be used as a function, use the following:

var x = inc(7)-1

Similarly, we can define an anonymous function in a number of parameters:

var mul = (x: Int, y: Int) => x*y

mul is now available as a function, use the following:

println(mul(3, 4))

We can not set the parameters for the anonymous function as follows:

var userDir = () => { System.getProperty("user.dir") }

userDir now available as a function, use the following:

println( userDir )

Scala function Scala function