8.24. Scala anonymous function

发布时间 :2023-11-16 23:00:02 UTC      

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

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.