Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: August 4, 2023
In this concise tutorial, we’re going to see how we can have access to the system environment variables in Kotlin.
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
In this tutorial, we saw that there is no difference in accessing system environment variables in Java and Kotlin.