8.24. Scala anonymous function

发布时间 : 2025-10-25 13:35:15 UTC      

Page Views: 10 views

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() ) 

8.24.1. 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 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。