Saturday, 16 August 2014

Scala Note 6: Singleton Objects in Scala

1.
Scala is more object-oriented than Java that classes in Scala cannot have static members and methods. Instead, Scala has singleton objects. A singleton object definition looks like a class definition, except instead of the keyword class you use the keyword object.

One difference between classes and singleton objects is that singleton objects cannot take parameters, whereas classes can. Each singleton object is implemented as an instance of a synthetic class(e.g. MyClass$). In particular, a singleton object is initialized the first time some code accesses it, and can't be instantiated with new.

When a singleton object shares the same name with a class, it is called that class's companion object.
A singleton object that does not share the same name with a companion class is called a standalone object.

To run a Scala program,  you must supply the name of a standalone singleton object with a main method that takes one parameter, an Array[String], and has a result type of Unit.

One difference between Scala and Java is that whereas Java requires you to put a public class in a file named after the class. In Scala, you can name .scala files anything you want, no matter what Scala classes or code you put in them.


object PolyTest extends Application {
  def dup[T](x: T, n: Int): List[T] =
    if (n == 0) Nil
    else x :: dup(x, n - 1)
  println(dup[Int](3, 4))
  println(dup("three", 3))
}

Please note that the trait Application is designed for writing short test programs, but should be avoided for production code as it may affect the ability of the JVM to optimize the resulting code; please use def main() instead.

2.

The syntax of an object definition follows the syntax of a class definition; it has an optional extends clause as well as an optional body. As is the case for classes, the extends clause defines inherited members of the object whereas the body defines overriding or new members. However, an object definition defines a single object only it is not possible to create other objects with the same structure using new. Therefore, object definitions also lack constructor parameters, which might be
present in class definitions.

Object definitions can appear anywhere in a Scala program; including at top-level. Since there is no fixed execution order of top-level entities in Scala, one might ask exactly when the object defined by an object definition is created and initialized. The answer is that the object is created the first time one of its members is accessed. This strategy is called lazy evaluation.

No comments:

Post a Comment