From Wikibooks, open books for an open world
Jump to navigation Jump to search

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[edit | edit source]

A simple example of an object:

object SimpleObject
val a = SimpleObject

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:

object MembersObject {
  val someValue = "test"
  def someMethod(a:Int) = a*a
println("someValue is: " + MembersObject.someValue) //Prints "someValue is: test".
println("someMethod(3) gives: " + MembersObject.someMethod(3)) //Prints "someMethod(3) gives: 9".

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

Uses[edit | edit source]

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.

println("Value of pi: " + math.Pi) //Prints "Value of pi: 3.141592653589793"
println("Square root of 4: " + math.sqrt(4)) //Prints "Square root of 4: 2.0"
println("Square root of 5: " + math.sqrt(5)) //Prints "Square root of 5: 2.23606797749979"

Another use of objects is to create instances of classes:

class Rectangle(val a:Int, val b:Int)
object Rectangle {
  def createValidRectangle(a:Int, b:Int) = new Rectangle(math.max(a, 1), math.max(b, 1))
val validRectangle = Rectangle.createValidRectangle(3, -10000)
println("Valid rectangle: " + validRectangle.a + ", " + validRectangle.b) //Prints "Valid rectangle: 3, 1".

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:

object ProgramEntryPoint {
  def main(args:Array[String]) = {
    println("Program execution start.")

    println("Program execution end.")

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