Scala: Write value to typesafe config object
Asked Answered
S

2

43

I'm using Typesafe config & have a config file in my resources directory which looks like this:

something {
  another {
    someconfig=abc
    anotherconfig=123
  }
}

How would I change the value of anotherconfig using scala?

Swanner answered 11/6, 2014 at 2:10 Comment(0)
R
93

If you want to change the loaded config (i.e. create a new config based on the old one), you can use withValue:

val newConfig = oldConfig.withValue("something.another.anotherconfig",
  ConfigValueFactory.fromAnyRef(456))
Rhines answered 11/6, 2014 at 6:56 Comment(0)
L
12

You can't overwrite a value in the original Config object since it's immutable. What you can do is create a new Config object with your values, using the original as a fallback. So:

val myConfig = ConfigFactory.parseString("something.another.anotherconfig=456")
val newConfig = myConfig.withFallback(oldConfig)

and then use newConfig everywhere instead of your original Config. A more maintainable option would be to have a 2nd config file with your changes and use:

val myConfig = ConfigFactory.load("local")
val oldConfig = ConfigFactory.load
val realConfig = myConfig.withFallback(oldConfig)

You could then use a System Property to set where to load myConfig from.

Leoni answered 12/6, 2014 at 13:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.