Unable to compile file in Scala

From the example in the book "Getting Started in Scala" script:

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 $ scalac ChecksumAccumulator.scala file, then generate an error: "not found: type ChecksumAccumulator val acc = new ChecksumAccumulator", tell me?

Thanks,

+4
source share
5 answers
Keyword

'object' defines a singleton object, not a class. Thus, you cannot create a new object; the keyword "new" requires a class.

check the Difference between an object and a class in Scala

+7
source

You probably left a code similar to

class ChecksumAccumulator {// ...}

+3
source

Other answers are correct when talking about what the problem is, but they don’t really help to understand why the example from the book seems to be wrong.

However, if you look at the Artima website, you will find an example in the 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 receive an error message.

+3
source

Your problem here

  val acc = new ChecksumAccumulator 

You cannot use a new keyword with an object. objects cannot be re-created. You always have a single instance of an object in scala. This is similar to static elements in java.

+2
source

Your code probably means companion . It is a kind of factory in imperative languages.

Basically, you have a couple of objects and a class . An object (singleton in imperative langs) cannot be created several times, as people have already noted here, and is usually used to define some static logic. In fact, there is only one instance - when you call it for the first time. But an object can have compaion - an ordinary class, and, as I think, you missed the definition of this ordinary class, so the object cannot see anyone other than itself.

The solution is to define this class or omit new (but I think that would be logically wrong).

0
source

Source: https://habr.com/ru/post/1388567/


All Articles