Scala/Objects

In Scala, an object is a named instance with members such as fields and methods. An object and a class that have the same name and which are defined in the same source file are known as companions. Companions has special access control properties, which is covered under Scala/Access modifiers.

Objects
A simple example of an object:

In the first line, the keyword "object" is used to define a new object, which is followed by the name of the object, which is here "SimpleObject". In the second line, a value named "a" is assigned the object instance named "SimpleObject".

The members of objects are similar to the members of classes. See Scala/Classes for more information. An example of members in an object:

Objects also support the special method "apply", for more information see Scala/Classes.

Uses
One use of objects is to contain fields and methods that are independent of any environment. One example is "math", which is the name of an object in the standard library which contains several fields and methods that only depend on arguments (if any) given to them.

Another use of objects is to create instances of classes:

In the above, invalid rectangles can still be constructed by using the constructor of class "Rectangle" directly. Scala/Visibility describes how to constrain access to constructors, which combined with objects makes it easier to ensure and verify that only valid class instances are created of some given class.

A third use of objects is to create the entry point to a Scala program. This is done by defining a "main" method with a specific signature:

The line "def main(args:Array[String])" indicates the required signature in order for the entry point to be valid. See Scala/Setup for more information.