in Scala. Apply method has different meanings, and for a function This method means invoking the function itself, the following excerpt from programming in Scala, 3rd Edition
Every function value is a instance of some class that extends one of the several functionn traits in the package Scala, such as F Unction0 for functions with no parameters, Function1 for functions with one parameter, and so on. Each functionn trait have an apply method, used to invoke the function.
In the Scala language, functions are objects, and each object is Scala. An instance of Functionn (1-22) where n is the number of function arguments, for example we define a function and copy it to a variable:
Scala> val f = (x:int) + x + 1= Int = <function1>
this defines a function that takes an integer variable as a parameter, and the function is to return the input parameter plus 1. You can see the ToString method of the Repl return parameter is <function0> . So if we have a reference to a function object, how do we call this function? The answer is through Functionn's apply method, which is functionn.apply () , so the method to invoke the function object is as follows:
Scala> f.apply (3= 4
But if each call to the method object passes through Functionn.apply (x, y ...), it will be a bit verbose, Scala provides a format that mimics the function call to invoke the function object
Scala> F (3= 4
Application Scenario Factory method
In Scala, a list object can be created by list.apply (1, 2, 3) , and the Apply method is defined in the associated object of the list class, and we can simplify the Apply method directly through list (1, 2, 3), as mentioned earlier. creates a list instance.
Collection Class
Several sub-trait of iterator iterators are mentioned in the Scala collection article, including SEQ, Set, and map, which inherit partialfunction and implement the Apply method, unlike the way they are implemented. We can use the following example to illustrate the application of apply
scala> Seq (1, 2, 3). Apply (1)//retrieve Res6:int = 2scala > Set (1, 2, 3). Apply (2)//Determine if there is res7:boolean = true scala > Map ("China", "Beijing", "US", "Washington"). Apply ("US" )//Find values by key res8:string = > Set (1, 2, 3) (2) Res9:boolean = true scala > Set (1, 2, 3) (2) Res10: Boolean = true scala > Map (" China "," Beijing "," Us "," Washington ") (" Us " = washington< /pre>
More application scenarios for apply to be accumulated later, the following article is a good explanation of the role of apply
Http://stackoverflow.com/questions/9737352/what-is-the-apply-function-in-scala
Use of apply in Scala