Environment Variables in Scala
Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables in Scala.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is empty.
The list of keys in the environment will depend on your particular machine.
If we set BAR
in the environment first, the running program picks that value up.
In Scala, we use sys.props
to set environment variables within the program, and sys.env
to access environment variables. Note that sys.env
returns a Map[String, String]
, which we can use to easily iterate over all environment variables.
The getOrElse
method is used on sys.env
to provide a default value (empty string in this case) if the key doesn’t exist in the environment.
Remember that changes made to sys.props
during runtime are not reflected in sys.env
, as sys.env
represents the environment variables at the time the JVM was started.