Andrew Li Andrew Li - 1 year ago 108
Scala Question

Using a global object or parameters to pass config data, which one is better in Scala?

I'm newbie to Scala, and I have years of experience programming in Java.

Usually there are two patterns passing some config:

  • Using a global object sounds like "ConfigManager". And every time I
    needs a config I get directly from it.

  • Passing the config through parameter. The config param may exists in
    many layers in the program.

I choose one pattern depends on how the config will be used when I'm writing Java.

But in Scala, many people talks about eliminating side effects. This makes me wonder if I should use the second patterns at any costs.

Which pattern is better in Scala?

Answer Source

Global objects are bad:

Make each component take it's configuration (individual pieces) as constructor parameters (possibly with some defaults). That prevents the creation of invalid components or components that have not been configured.

You can collect the initial processing of configuration values in a single class to centralize configuration code and to fail-fast when things are missing. But don't make your components (classes needing the configuration) depend on a global object or take in an entire configuration as a parameter. Just what they need as constructor params.


// centralize the parsing of configuration
case class AppConfig (config: Config) {
  val timeInterval = config.getInt("type_interval")
  val someOtherSetting = config.getString("some_other_setting")

// don't depend on global objects
class SomeComponent (timeInterval: Int) {

object SomeApplication extends App {
  val config = AppConfig(ConfigFactory.load())

  val component = new SomeComponent(config.timeInterval)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download