0

My class currently looks like:

class WebConfig(config: Config) {

  def this() {
     this(ConfigFactor.load())
  }

  def dbPort = config.getInt("mysql.port")

}

I don't like that when I call dbPort, it has to call and then cast the config each and every time.

So I want to create private fields and set them in the constructor, so then calling dbPort will simply return what a private field has.

How can I do this?

I tried creating a private var but I am getting this error:

 class WebConfig(config: Config) {
      private var _dbPort: Int
      def this() {
         this(ConfigFactor.load())

         _dbPort = config.getInt("mysql.port")
      }

      def dbPort: Int = _dbPort

    }

Error:

abstract member may not have private modifier
1
  • 3
    While this does not answer the question, doesn't declaring lazy val dbPort = config.getInt("mysql.port") do exactly what you are trying to implement? Commented Nov 19, 2014 at 14:08

2 Answers 2

6

You are getting that error because your private variable is not initially assigned a value, so is treated as abstract, and abstract variables can't be private because they can not be accessed by the sub classes that are required to implement them.

To fix this you can assign a placeholder value to your variable like this:

private var _dbPort: Int = _

That being said, I think vptheron and kululimpa's suggestions are the way to go.

Sign up to request clarification or add additional context in comments.

Comments

2

Can't you just write this:

class WebConfig(config: Config) {

  def this() {
     this(ConfigFactor.load())
  }

  val dbPort = config.getInt("mysql.port")

}

It will only read the config parameter one time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.