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