페이지

2015년 11월 2일 월요일

Scala2e Chapter4 Classes and Objects 4.3 Singleton objects

Scala connot have static members.
Instead, Scala has singleton objects.
except instead of the keyword class you use the keyword object.

import scala.collection.mutable.Map

object ChecksumAccumulator{

     private val cashe = Map[String, Int]()
     def ccalculate(s: String) : Int =
          if(cache.contains(s))
               cache(s)
          else {
               val acc = new CheckSumAccumulator
               for(c <- p="" s="">                   acc.add(c.toByte)
               val cs = acc.checksum()
               cache += (s -> cs)
                cs
          }
  }

If you are a Java programmer, on way to thick of singleton objects is as the home for any static methods you might have written in Java.

ChecksumAccumulator.calculate("Every value is an object.")

A singleton object is more than a holder of satic methods, however, It is a first-class object. You can think of a singleton object's name, therefore, as a "name tag" attached to the object:



Defining a singleton object doesn't define a type(at the Scala level of abstraction).
Singleton objects extends a superclass and can mix in traits. Given each singleton object is an instance of its superclasses and mixed-in traits, you can invoke its methods via these types, refer to it from variables of these types, and pass it to methods expecting these types.

One difference between classes and singleton objects is that singleton objects cannot take parameters, whereas classes can.

Because you can't instantiate a singleton object with the new keyword, you have no way to pass parameters to it.
Each singleton object is implemented as an instance of a synthetic class referenced from a static variable, so they have the same initialization semantics as Java statics.
In particular, a singleton object is initialized the first time some code accesses it.

A singleton object that does not share the same name with a companion class is called a standalone object.
   

댓글 없음: