One way in which Scala is more object-oriented than java is that classes in Scala cannot have static members. Instead, Scala has singleton objects. A singleton object definition looks like a class definition, except instead of the key word class you use the keyword object.
When a singleton object shares the same name with a class, it is called that class’s companion object. You must define both the class and it’s companion object in the same source file. The class is called the companion class of the singleton object.
A class and it’s companion object can access each other’s private members.
**When you are writing an object and you have a class of the classes very name the object goes into the the class file.
Note ChecksumAccumulator.scala:
class ChecksumAccumulator {
private var sum = 0
def add(b: Byte): Unit = {
sum += b
}
def checksum(): Int = {
return ~(sum & 0xFF) + 1
}
}
import scala.collection.mutable.Map
object ChecksumAccumulator{
private val cache = Map[String, Int]()
def calculate(s: String): Int =
if (cache.contains(s))
cache(s)
else{
val acc = new ChecksumAccumulator
for (c <- s)
acc.add(c.toByte)
val cs = acc.checksum()
cache += (s -> cs)
cs
}
}
Programming in Scala, Second Edition
Martin Odersky (Author), Lex Spoon (Author), Bill Venners (Author)
**my comment