Apply ():
The Apply method provides a good syntax mechanism when a class or object has a primary purpose
Classclass Fooscalaobject foomaker { | New Foo | }defined module Foomakerscala> Val newfoo == [email protected]
When written in object, use the method: Class name ()
Or
class Bar { | 0 | class Barscalanew= [email protected]47711479Scala >0
When writing in class, use the method: variable name ().
Associated objects, associated classes:
In Scala, you can think of statements in object as static statements in other languages such as Java, which are owned by the class, not specific objects.
When object and class names are the same, they are referred to as the associated objects and associated classes of each other, and the statements in the associated object are static parts of the class.
The associated object is usually used as a factory pattern, i.e. it can be made into a singleton object.
Single-instance objects:
class Private {}object Bar { new bar = instance}
Apply Companion Object Singleton object