Reading Time: 2 minutes

In this blog we will discuss about the better way of loading the configuration of certain types. Now a days we use typesafe config for the same purpose. PureConfig also uses typesafe config internally but also provides the better way of doing this.

PureConfig is not a configuration library, it can be seen as a better front-end for the existing libraries. It uses the Typesafe Config library for loading raw configurations and then uses the raw configurations to do its magic.

The goal of PureConfig is to create at compile-time the boilerplate necessary to load a configuration of a certain type. In other words, you define what to load and PureConfig provides how to load it.

To use the PurConfig, we need to add dependency in build.sbt for scala 2.11, 2.12:

"com.github.pureconfig" %% "pureconfig" % "0.7.2"

Now define the config in application.conf file :

company { full-name = "Knoldus Software LLP" started = 2012 employees = "80-120" offices = ["India", "Singapore", "US", "Canada"] offices-in-india { head-office = "Delhi" development = "Noida" } }

You can see above, there are different types of values present in config i.e. List, Map, String, Int

Now Define the scala types for config to be converted :

case class Company(company: CompanyDetails) case class CompanyDetails(fullName: String, started: Int, employees: String, offices: List[String], officesInIndia: Map[String, String], extraActivity: Option[String])

By analyzing config and the case class you will notice that field’s name in config is in Kebab case (full-name) while in case class it is in camel case (fullName). This is the default behavior. We will see the customize behavior for defining field’s name in the coming blogs.

Now load the config :

import pureconfig.error.ConfigReaderFailures import pureconfig.loadConfig val simpleConfig: Either[ConfigReaderFailures, Company] = loadConfig[Company] simpleConfig match { case Left(ex) => ex.toList.foreach(println) case Right(config) => println(s"Company's Name ${config.company.fullName}") println(s"Company started at ${config.company.started}") println(s"Company's strength is ${config.company.employees}") println(s"Company's presence are in ${config.company.offices}") println(s"Company's office in India are ${config.company.officesInIndia}") println(s"Company's extra activity is ${config.company.extraActivity}") }

That’s it. Hope you enjoy the reading.

You can get the full code here.

Happy Blogging !!!