Search code examples
scalaplayframework-2.0typesafetypesafe-config

Scala - play2 config get section


I decided to try scala out with play2. I am trying to somehow get a config section out of application config. It looks like this (by section I mean whole mail part)

services: {
  rest: {
    mail: {
      uri: "xyz",
      authorization: {
        username: "xyz",
        password: "xyz"
      }
    }
  }
}

Code

import com.typesafe.config.ConfigObject
import play.api.Play.current

val config: Option[ConfigObject] = current.configuration.getObject("services.rest.mail")

This gives Some(SimpleConfigObject()) and trough there the only way I am able to actually get mail section and use it as a ConfigObject is trough

config.get.toConfig.getString("uri")

Or I can get the actual value with

config.get.get("uri").unwrapped().toString

Or for fun:

config.get.toConfig.getObject("authorization").toConfig.getString("username")

Either way it seems to me I am doing it overly complicated. Is there some easier way to get a section from config?


Solution

  • I will post this as an answer for future reference.

    After another while of playing with the code I have found parseResourcesAnySyntax method which does exactly what I want and since I have my config split into multiple parts for separate environments (application.dev.conf, etc.) I can simply do

    import com.typesafe.config.{Config, ConfigFactory}
    import play.api.Play._
    
    val config: Config = ConfigFactory.parseResourcesAnySyntax("application.%s.conf" format current.mode)
    

    and then use

    config.getString("uri")
    
    // or
    
    config.getString("authorization.username")
    
    // or if I want to use part of it as another section
    
    val section: Config = config.getConfig("authorization")
    section.getString("username")
    

    Of course, another viable alternative is using a wrapper as mister Stebel recommended.