In Scala, if I have the following config:
id = 777
username = stephan
password = DG#%T@RH
The idea is to open a file, transform it into a string, do getLines
on it and get the right-hand side value based on the left-hand side key. What would be the nicest code to read constant configuration values into my app?
Client usage: val username = config.get("username")
load. Loads an application's configuration from the given classpath resource or classpath resource basename, sandwiches it between default reference config and default overrides, and then resolves it.
Configurations from a fileBy default, the ConfigFactory looks for a configuration file called application. conf. If willing to use a different configuration file (e.g.: another. conf), we just need to indicate a different file name and path to load (e.g.: ConfigFactory. load("another")).
Play uses the Typesafe config library, but Play also provides a nice Scala wrapper called Configuration with more advanced Scala features. If you're not familiar with Typesafe config, you may also want to read the documentation on configuration file syntax and features.
PureConfig is a Scala library for loading configuration files. It reads Typesafe Config configurations written in HOCON, Java . properties , or JSON to native Scala classes in a boilerplate-free way. Sealed traits, case classes, collections, optional values, and many other types are all supported out-of-the-box.
Best way would be to use a .conf
file and the ConfigFactory
instead of having to do all the file parsing by yourself:
import java.io.File
import com.typesafe.config.{ Config, ConfigFactory }
// this can be set into the JVM environment variables, you can easily find it on google
val configPath = System.getProperty("config.path")
val config = ConfigFactory.parseFile(new File(configPath + "myFile.conf"))
config.getString("username")
I usually use scalaz Validation
for the parseFile
operation in case the file it's not there, but you can simply use a try/catch
if you don't know how to use that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With