1. Overview
In this concise tutorial, we’re going to see how we can have access to the system environment variables in Kotlin.
2. Reading Environment Variables
To read an environment variable in Kotlin, we can use the System.getenv(String) method. Similar to what we usually do in Java, we can write:
val env = System.getenv("HOME")
assertNotNull(env)
This verification should pass, assuming that there’s an environment variable named HOME on the system. Also, if the given environment variable does not exist, this method will return null:
assertNull(System.getenv("INVALID_ENV_NAME"))
Finally, if we don’t pass anything to the getenv() method, it returns all available environment variables on the system as a Map<String, String>:
val allEnvs = System.getenv()
allEnvs.forEach { (k, v) -> println("$k => $v") }
assertThat(allEnvs).isNotEmpty
This should print all the environment variables:
KUBECONFIG => /Users/Ali/.kube/config
LC_TERMINAL => iTerm2
DEFAULT_USER => Ali
// omitted
3. Conclusion
In this tutorial, we saw that there is no difference in accessing system environment variables in Java and Kotlin.
As usual, all the examples are available over on GitHub.