Lukasz Madon
Lukasz Madon

Reputation: 14994

private field in object doesn't compile

I tried to run one example from Programming in Scala but compiler gives me error:

Description Resource Path Location Type illegal start of statement (no modifiers allowed here) ChecksumAcc.sc /HelloWorld/src line 3 Scala Problem

basically complains about private

import scala.collection.mutable.Map

object ChecksumAcc {
    private val cache = Map[String, Int]()

}

I'm using Eclipse for Scala worksheet. Same after updating. I believe it uses 2.9.3 scala compiler. Why doesn't it compile?

Upvotes: 0

Views: 427

Answers (2)

Srikanth
Srikanth

Reputation: 11

To avoid the error message you are seeing, when you are working in a Eclipse Scala work sheet wrap the Class definition and Companion class (Singleton object) in the same object

object worksheet { 
 class CheckSumAccumulator {
 ... 
 } 
  object CheckSumAccumulator { 
  ... 
  } 
  CheckSumAccumulator.calculate("foobar")

}

Upvotes: 0

user500592
user500592

Reputation:

Not sure what your actual question is, but the Scala worksheet has some special rules (as indicated by the very clear error message...). One thing you can do if you have to use the worksheet, is to put all your code inside a Worksheet object like this:

object Worksheet {
  import scala.collection.mutable.Map

  object ChecksumAcc {
    private val cache = Map[String, Int]()
  }
}

Or alternatively, use Eclipse's "New Scala object..." and use that instead of the worksheet.

Upvotes: 2

Related Questions