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")

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:


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") }

This should print all the environment variables:

KUBECONFIG => /Users/Ali/.kube/config
// 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.

Comments are closed on this article!