Scala anonymous function

Scala provides a relatively lightweight syntax for defining anonymous functions. Anonymous functions in source code are called function literals, and at runtime, function literals are instantiated as objects of the called function values.

Scala supports first-class functions, which means that functions can be expressed in functional literal syntax, i.e., (x: Int) => x + 1, and functions can be represented by objects, which are so-called function values. The following expression creates an integer successor function:

var inc = (x:Int) => x+1
The variable inc can now use the function in the usual way:

var x = inc(7)-1
Alternatively, you can use Functions defined with multiple arguments are as follows:

var mul = (x: Int, y: Int) => x*y
The variable mul can now use the function in the usual way:

println(mul(3, 4))
Alternatively, you can The function is defined with no parameters as follows:

var userDir = () => { System.getProperty("user.dir") } The
variable userDir can now use the function in the usual way:

println( userDir )

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327046525&siteId=291194637