5

From an example in book "Begining in Scala", the script is:

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
  }
}

but, when I tried to compile this file $scalac ChecksumAccumulator.scala, then generate an error, "not found: type ChecksumAccumulator val acc = new ChecksumAccumulator", any suggest?

Thanks,

5 Answers5

7

'object' keyword defines a singleton object, not a class. So you can't new an object, the 'new' keyword requires a class.

check this Difference between object and class in Scala

Community
  • 1
  • 1
Zang MingJie
  • 5,164
  • 1
  • 14
  • 27
3

You probably left some code out that looks like

class ChecksumAccumulator { //... }

Silvio Bierman
  • 703
  • 5
  • 9
3

The other answers are correct in saying what the problem is, but not really helping you understand why the example from the book is apparently not correct.

However, if you look at the Artima site, you will find the example is in a file here

Your code is an incomplete fragment. The file also includes these lines

// In file ChecksumAccumulator.scala
class ChecksumAccumulator {
  private var sum = 0
  def add(b: Byte) { sum += b }
  def checksum(): Int = ~(sum & 0xFF) + 1
}

... without which you will get the error you had.

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
2

your issue is here

 val acc = new ChecksumAccumulator

you cannot use new keyword with the object. objects cannot be re-instantiated. You always have single instance of an object in scala. This is similar to static members in java.

vkantiya
  • 1,343
  • 1
  • 8
  • 20
0

Your code, probably meant as a companion object. That's kinda factories in imperative languages.

Basicaly, you have object and class pair. Object (singleton in imperative langs) can't be instantiated multiple times, as people here already noted, and usually used to define some static logic. In fact, there is only one instantiation -- when you call him for the first time. But object can have compaion -- regular class, and, as I think you've missed definition of that regular class, so object can't see anyone else, but itself.

The solution is to define that class, or to omit new (but i think that would be logicaly wrong).

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228