Pergunta

I want to turn Typesafe configuration

root {
  mainA = "test"
  submodule {
    paramA = "value"
    paramB = "value"
  }
  anotherModule {
    zoo = 1
    sub {
      z = test
    }
  }
}

into some sort of Scala configuration object like

object config {

  val cfg = ConfigFactory.load()

  val root = "root"

  lazy val mainA = cfg.getString("root.mainA")

  object submodule {
    lazy val paramA = cfg.getString("root.submodule.paramA","value")
    lazy val paramB = cfg.getString("root.submodule.paramB","value")
  }

  object anotherModule {
    lazy val zoo = cfg.getInt("root.anotherModule.zoo",1)
    object sub {
      lazy val z = cfg.getString("root.anotherModule.sub.z","test")
    }
  }
}

So in general I will have some "template" configuration file, and generate "Generic" configuration object with some defaults.

in Haskell I would use Template Haskell in order to generate and compile the code, what can I do about that in Scala?

Foi útil?

Solução

If you wish to have a convenient way to use config from the Scala code, you may try to use Dynamic ancestor to access config. Something like:

class RichConfig(cfg:Config) extends Dynamic {
  private val `intClassTag` = implicitly[ClassTag[Int]]
  def selectDynamic[T](fieldName:String)(implicit ct:ClassTag[T]) = 
    ct match {
      case `intClassTag` =>
        cfg.getInt(fieldName)
    }
}

Of course it doesn't give you runtime check for existence of the configuration items.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top