Reputation: 53806
I'm reading 'Programming in scala' and in one of the example when I try to compile it in Eclipse I receive error : 'not found: type ChecksumAccumulator' The type is declared as below. Is the code below correct ?
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.toBye)
val cs = acc.checksum()
cache += (s -> cs)
cs
}
}
Upvotes: 0
Views: 9631
Reputation: 6519
The problem is that in the book class is defined too early and later in the file ChecksumAccumulator.scala class definition is not there. For a beginner it is enough to mislead and will get stuck. This must be the complete code for the two files.
In ChecksumAccumulator.scala
import scala.collection.mutable.Map
class ChecksumAccumulator {
private
var sum = 0
def add(b: Byte) {
sum += b
}
def checksum(): Int = ~(sum & 0xFF) + 1
}
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
}
}
In Summer.scala
import ChecksumAccumulator.calculate
object Summer {
def main(args: Array[String]) {
for (arg < -args)
println(arg + ": " + calculate(arg))
}
}
Then you can compile using.
scalac ChecksumAccumulator.scala Summer.scala
Then run the example with
scala Summer of love
Which will give you the below output:
of: -213
love: -182
Upvotes: 0
Reputation: 139038
From Programming in Scala:
The singleton object in this figure is named
ChecksumAccumulator
, the same name as the class in the previous example. 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 its companion object in the same source file. The class is called the companion class of the singleton object.
If you try to compile this code alone, without the ChecksumAccumulator
class, you'll get a compiler error because you can't create an instance of a singleton object with new
.
The book does a great job of explaining how companion objects and classes work together, and since you're already reading it I won't bother adding any further summary here.
Upvotes: 1