Standalone objects are singleton objects which are not attached to any class, i.e., they don’t have the same name as any class. Hence, they can literally stand alone.
Up until now, we haven’t been able to execute our ChecksumAccumulator program. This is where standalone objects come in. They can be used for defining the entry point of a Scala application, an executable program. To use a standalone object for this purpose, you need to create a main method that takes a single parameter of type Array[String] (an array of strings). Now all you have to do when you want to execute your program is run the standalone object.
Let’s define a standalone object for our ChecksumAccumulator program so it can be used as an application.
xxxxxxxxxx
import scala.collection.mutable
class ChecksumAccumulator {
private var sum = 0
def add(b: Byte) = sum += b
def checksum() = ~(sum & 0xFF) + 1
}
//companion object of ChecksumAccumulator
object ChecksumAccumulator {
private val cache = mutable.Map.empty[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
}
}
//standalone object that acts as an entry point for the ChecksumAccumulator application
import ChecksumAccumulator.calculate
object EntryApplication {
def main(args: Array[String]) = {
for(arg<-args)
println(arg + ": " + calculate(arg))
}
}