Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read environment variables in Scala

People also ask

How do I view environment variables in Python?

getenv() method is used to extract the value of the environment variable key if it exists. Otherwise, the default value will be returned. Note: The os module in Python provides an interface to interact with the operating system.

What is System Getenv in Java?

getenv(String name) method gets the value of the specified environment variable. An environment variable is a system-dependent external named value. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH).


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.


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

Same way:

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

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.


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