Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read values from config in Scala

Tags:

file

scala

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 getLineson 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")

like image 816
Stephan Rozinsky Avatar asked Mar 10 '15 14:03

Stephan Rozinsky


People also ask

What does ConfigFactory load () do?

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.

What is ConfigFactory in Scala?

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")).

What is configuration in Scala?

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.

What is PureConfig?

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.


1 Answers

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.

like image 140
Ende Neu Avatar answered Sep 19 '22 18:09

Ende Neu