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.
import scala.jdk.CollectionConverters._
import scala.util.Properties
object EnvironmentVariables {
def main(args: Array[String]): Unit = {
// To set a key/value pair, use `sys.props`. To get a
// value for a key, use `sys.env`. This will return
// None if the key isn't present in the environment.
sys.props("FOO") = "1"
println(s"FOO: ${sys.env.getOrElse("FOO", "")}")
println(s"BAR: ${sys.env.getOrElse("BAR", "")}")
// Use `sys.env` to list all key/value pairs in the
// environment. This returns a Map[String, String].
// Here we print all the keys.
println()
sys.env.keys.foreach(println)
}
}
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is empty.
$ scala EnvironmentVariables.scala
FOO: 1
BAR:
TERM_PROGRAM
PATH
SHELL
...
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.
$ BAR=2 scala EnvironmentVariables.scala
FOO: 1
BAR: 2
...
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.