Case Class Instantiation From Typesafe Config

Ramón J Romero y Vigil picture Ramón J Romero y Vigil · Jul 27, 2016 · Viewed 9.7k times · Source

Suppose I have a scala case class with the ability to serialize into json (using json4s or some other library):

case class Weather(zip : String, temp : Double, isRaining : Boolean)

If I'm using a HOCON config file:

allWeather {

   BeverlyHills {
    zip : 90210
    temp : 75.0
    isRaining : false
  }

  Cambridge {
    zip : 10013
    temp : 32.0
    isRainging : true
  }

}

Is there any way to use typesafe config to automatically instantiate a Weather object?

I'm looking for something of the form

val config : Config = ConfigFactory.parseFile(new java.io.File("weather.conf"))

val bevHills : Weather = config.getObject("allWeather.BeverlyHills").as[Weather]

The solution could leverage the fact that the value referenced by "allWeather.BeverlyHills" is a json "blob".

I could obviously write my own parser:

def configToWeather(config : Config) = 
  Weather(config.getString("zip"), 
          config.getDouble("temp"), 
          config.getBoolean("isRaining"))

val bevHills = configToWeather(config.getConfig("allWeather.BeverlyHills"))

But that seems inelegant since any change to the Weather definition would also require a change to configToWeather.

Thank you in advance for your review and response.

Answer

Nazarii Bardiuk picture Nazarii Bardiuk · Jul 27, 2016

typesafe config library has API to instantiate object from config that uses java bean convention. But as I understand case class does not follow those rules.

There are several scala libraries that wrap typesafe config and provide scala specific functionality that you are looking for.

For example using pureconfig reading config could look like

val weather:Try[Weather] = loadConfig[Weather]

where Weather is a case class for values in config