How to read environment variables in Scala

ScalaEnvironment Variables

Scala Problem Overview


In Java, reading environment variables is done with System.getenv().

Is there a way to do this in Scala?

Scala Solutions


Solution 1 - Scala

Since Scala 2.9 you can use sys.env for the same effect:

scala> sys.env("HOME")
res0: String = /home/paradigmatic

I think is nice to use the Scala API instead of Java. There are currently several project to compile Scala to other platforms than JVM (.NET, javascript, native, etc.) Reducing the dependencies on Java API, will make your code more portable.

Solution 2 - Scala

There is an object:

scala.util.Properties

this has a collection of methods that can be used to get environment info, including

scala.util.Properties.envOrElse("HOME", "/myhome" )

Solution 3 - Scala

Same way:

scala> System.getenv("HOME")
res0: java.lang.String = /Users/dhg

Solution 4 - Scala

Using directly a default with getOrElse over the sys.env Map (val myenv: Map[String, String] = sys.env):

sys.env.getOrElse(envVariable, defaultValue)

You get the content of the envVariable or, if it does not exist, the defaultValue.

Solution 5 - Scala

If Lightbend's configuration library is used (by default in Play2 and Akka) then you can use

foo = "default value" foo = ${?VAR_NAME}

syntax to override foo if an environment variable VAR_NAME exist. More details in https://github.com/typesafehub/config#optional-system-or-env-variable-overrides

Solution 6 - Scala

To print all environment variables, you can use

System.getenv.forEach((name, value) => println(s"$name: $value"))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsummerbulbView Question on Stackoverflow
Solution 1 - ScalaparadigmaticView Answer on Stackoverflow
Solution 2 - ScalaandyView Answer on Stackoverflow
Solution 3 - ScaladhgView Answer on Stackoverflow
Solution 4 - ScalavicteView Answer on Stackoverflow
Solution 5 - ScalajfuentesView Answer on Stackoverflow
Solution 6 - ScalaMatthias BraunView Answer on Stackoverflow