0

ScalaStyle doesn't allow mutable variables. Sample code:

object Configuration {

  var auroaDbConfig: AuroraConnectionParameter = null
  def getConfigration() = {
    val rootConfig: Config = ConfigFactory.load()
    //for aurora configuration
    auroaDbConfig = rootConfig
      .as[AuroraConnectionParameter]("mdpApp.aurora")
    //for spark configuration
    val sparkConfig: SparkConnectionParameter = rootConfig
      .as[SparkConnectionParameter]("mdpApp.spark")
    //for cassandra configuration
    val cassandraDbConfig: CassandraConnectionParameter = rootConfig
      .as[CassandraConnectionParameter]("mdpApp.cassandra")
    //for s3 configuration
    val s3Config: S3ConnectionParameter = rootConfig
      .as[S3ConnectionParameter]("mdpApp.s3")

  }

}

Use Case : the ConfigFactory.load() is to be called only once so placed it into a function which would be called once in the code & other variable are called as per required in the code

How do I refactor the code, so that variables are initliazed in the functions and called when and where required in the code

2 Answers 2

2

Key word lazy is exactly for this case. We wanna load something once, but only load only when we need it.

Without keyword lazy in this example is also OK.

object Configuration {

  lazy val rootConfig: Config = ConfigFactory.load()
  lazy val auroaDbConfig: AuroraConnectionParameter = rootConfig
      .as[AuroraConnectionParameter]("mdpApp.aurora")
  lazy val sparkConfig: SparkConnectionParameter = rootConfig
      .as[SparkConnectionParameter]("mdpApp.spark")
    //for cassandra configuration
  lazy val cassandraDbConfig: CassandraConnectionParameter = rootConfig
      .as[CassandraConnectionParameter]("mdpApp.cassandra")
    //for s3 configuration
  lazy val s3Config: S3ConnectionParameter = rootConfig
      .as[S3ConnectionParameter]("mdpApp.s3")

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

Comments

0
  def getConfigration() : AuroraConnectionParameter = {
    val result = rootConfig
      .as[AuroraConnectionParameter]("mdpApp.aurora")
    // snip
    result
  }
  val auroaDbConfig = getConfiguration()

I believe will do what you are asking, if I understand your question correctly. You could also, of course, just execute that rootConfig.as[AuroraConnectionParameter]... as the last statement in the function and it will behave the same as capturing the variable and returning it. Whichever fits your style and other constraints.

1 Comment

But this is not just one variable, I have 4 similar variables.And have to make sure that rootconfig is declared only once

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.