Apply: When you pass one or more arguments to a variable (object) in parentheses, Scala turns it into a call to the Apply method
Val Array=array (1,2,3,4,5,6)
Array (0), the operation of the first element of the array is converted to the array.apply (0) operation, which also explains why the Scala array value is not enclosed in parentheses, because it is also a method call.
Anyobject ("Key1") will be converted to anyobject.apply ("key") operation, which will also let us think of the MAP's value-taking operation
Class SomeClass {
def apply (key:string): String ={
println ("Apply method called, key is:" + key)
"Hello world!"
}
}
Val Anyobject =new SomeClass
println (Anyobject ("Key1"))
The output after execution is:
Apply method called, key Is:key1
Hello world!
The description is called to the appropriate apply method.
When we construct an Array or MAP, we will simply write
Val numnames =array ("zero", "one", "one")
The function above is like the Apply factory method of the called Array class. The same example of a singleton object also explains the invocation of the associated object's apply method.
Object EMail {
def apply (user:string, domain:string): String ={
println ("Apply method called")
println (user + "@" + domain)
}
}
Val Email =email ("lyrebing", "hotmail.com")
println (email)
The associated class and the associated object apply
Class applytest{
def apply () =println ("I am into Spark somuch!")
def haveatry{
println ("A Try on apply!")
}
}
Object applytest{
def apply () ={
println ("I am into Scala somuch!")
New Applytest
}
}
Object applyoperation{
def main (args:array[string]) {
Val A=applytest ()
A.haveatry
I am into Scala somuch!
There is a try on apply!
Val b=new applytest
B.haveatry
println (b ())//Invoking the class's Apply method
There is a try on apply!
I am into Spark somuch!
}
}