1: Associated objects and apply method
If a class has the same name as an object, then we consider them to be associated with each other. object is the associated object of class. As shown, object apply is the associated object of class apply.
A small detail to note is that the Apply function of the associated object needs to be added with a pair of "()" even if there are no parameters.
class Apply { = { println ("class Apply") } = println ("Class Test")}object apply{ = {// Note here the Apply () function definition cannot omit () println ("object Apply") even if there are no arguments New Apply } extends app{ = Apply () apply.test}
We can implement the Apply function in the associated object, do something in the function, if we want to get an instance of the class object, but not through new way, then it will first execute the class of the associated object of the Apply function
Execute the above code, the result:
Object apply
Class Test
As you can see, the first line of code gets an apply object, which first executes the apply () of the associated object, and then executes the class apply's test () to indicate that it is indeed a class apply object.
Application of Apply:
For example, can be used to implement a single case, requires two steps, a class of the structure of the private, two in the class of the associated object implementation of the Apply function, here return class object.
classApplyPrivate{//privatization of constructor functionsdef apply ={println ("Class Apply")} def Test= println ("Class test")}object apply{val apply_i=NewApply ()//the associated object can access the private properties and functions of the classdef apply () = {//Note that the Apply () function definition here cannot be omitted (), even if there are no arguments.println ("Object Apply") apply_i}}object main_extendsapp{//val apply = apply ()//apply.test for(I <-0 until 10) {val apply_i=Apply () println (apply_i)}}
Execute code Result:
You can see that both are the same object.
Scala companion objects, apply () and Singleton