Developus
Developus

Reputation: 1462

Scala - how to set data into placeholder from config file?

I have a simple application.conf file:

smth="smth ${data}"

The data is a placeholder which I would like to fill with some data given by te user. I read the config file, but I really have no idea how I can pass given data into this String. The only idea is to use replace on String, but I think it is not best solution:

def fill(arg: String) = {
  val config = ConfigFactory.load("application.conf").getString("smth")
  println(config.replace("${data}", arg))
}

Is it possible to write it in a cleaner way? I tried also to do some "magic" with string interpolation, but I failed.

Upvotes: 3

Views: 1179

Answers (3)

Mario Galic
Mario Galic

Reputation: 48410

Consider concatenation in combination with programatically setting system properties before loading the config like so

smth="smth "${data}

and then

def fill(arg: String) = {
  System.setProperty("data", arg) // make sure to set before loading config
  val config = ConfigFactory.load("application.conf")
  println(config.getString("smth") 
}

This way ${data} gets substituted with data system property on load.

Upvotes: 2

sarveshseri
sarveshseri

Reputation: 13985

The simplest way is to add an environment variable named data and then resolve the config with default config-resolvers which will pick up the environment variables.

val config = ConfigFactory.load("application.conf").resolve()

Other way is to provide a supplementary config, which can be used to resolve the placeholders,

import scala.collection.JavaConverters._

val resolveConfig = ConfigFactory.parseMap(Map("data" -> "abc").asJava).resolve()

Or,

val resolveConfig = ConfigFactory.parseString("""data: abc""").resolve()

Then use this to resolve your config,

val config = ConfigFactory.load("application.conf").resolve(resolveConfig)

Now, you can read your string from config,

val smthString = config.getString("smth")

Upvotes: 3

YouXiang-Wang
YouXiang-Wang

Reputation: 1127

If there is some workaround by %s?

smth="smth %s"


def fill(arg: String) = {
  val config = ConfigFactory.load("application.conf").getString("smth")
  println(config.format(arg))
}


Upvotes: 5

Related Questions