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.

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#Members for more information. An example of members in an object:

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.

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: