The Apply of Scala learning

Source: Internet
Author: User

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!
}

}










Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.