Scala learns the static in 16–scala

Source: Internet
Author: User

In the first two sections, we learned about Scala's objects and associated objects, both of which are used to mean the static members of Java.

There are no static fields and static methods in Scala. A static member destroys the complete object-oriented model that Scala supports. However, it is possible to implement class-level operations on Scala through the associated object.

Go back and look again at that marker example, and make a few tweaks:

classMarker Private(Val color:string) {println ("Creating" + This) override Def toString (): String= "Marker Color" +color}object Marker {PrivateVal markers = Map ("Red"NewMarker ("Red"),    "Blue"NewMarker ("Blue"),    "Green"NewMarker ("Green")) def primarycolors= "Red, green, blue"def apply (color:string)=if(Markers.contains (color)) markers (color)Else NULL}println ("Primary colors is:" +marker.primarycolors) println (Marker ("Blue")) println (Marker ("Red"))

In the adjusted code, a Primarycolors method is declared for the marker object using the DEF keyword, which returns a string "red, Green, blue" (if there are no arguments, the parentheses in the method can be omitted, And return can also be omitted). This method is called in the same way as a static method in Java.

There is another benefit to using the companion object: You can create an instance of the associated class without using the new keyword. This relies primarily on the Apply method, which is the syntactic sugar provided by Scala. The above code, when calling marker ("blue"), is actually calling marker.apply ("Blue"). This approach makes it easier to create and retrieve instances.

Take a look at the results of this method:

Scala learns the static in 16–scala

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.