1. Overview

In this tutorial, we are going to see how we can read environment variables in Scala.

Environment variables allow us to define values for given keys on the OS, which applications can read. We typically use them for some configurations, such as the path where to read a file.

2. Reading Environment Variables

As in most programming languages, Scala allows us to read environment variables. There are a few different ways to do it, but they are very similar, so it’s a matter of personal preference more than anything.

2.1. Using Scala’s sys Object

The most common and idiomatic way to read environment variables in Scala is by using the sys package object, which puts the environment variables into an immutable. Map[String, String]:

scala> sys.env
res0: scala.collection.immutable.Map[String,String] = HashMap(JAVA_MAIN_CLASS_27606 -> scala.tools.nsc.MainGenericRunner, PWD -> /private/tmp, JAVA_ARCH -> x86_64)

scala> sys.env.get("PWD")
res1: Option[String] = Some(/private/tmp)

The scala sys object is just a thin wrapper around the java code we saw in the previous section, but it makes things much more idiomatic as it doesn’t return nulls if the variable doesn’t exist.

2.2. Using Scala’s Properties Object

There’s still another way to read environment variables, although not that common. It consists of using scala.util.Properties object:

scala> scala.util.Properties.envOrElse("PWD", "undefined")
res0: String = /private/tmp

scala> scala.util.Properties.envOrElse("RANDOM-VAR-FOO", "undefined")
res1: String = undefined

scala> scala.util.Properties.envOrNone("PWD")
res2: Option[String] = Some(/private/tmp)

2.3. Using Java’s System Object

Since Scala offers interoperability with Java, we can use the same utilities from Java:

scala> System.getenv()
res0: java.util.Map[String,String] = {JAVA_ARCH=x86_64, JAVA_MAIN_CLASS_27606=scala.tools.nsc.MainGenericRunner, PWD=/private/tmp}

scala>  System.getenv("PWD")
res1: String = /private/tmp

scala>  System.getenv("RANDOM-VAR-FOO")
res2: String = null

3. Conclusion

In this article, we saw the different ways to read environment variables in Scala. While there are a few ways to do it, they are very similar and straightforward.

guest
0 Comments
Inline Feedbacks
View all comments