This post will discuss how to read the value of an environment variable in Kotlin.

1. Using System.getenv() function

The standard solution is to use the System.getenv(), which returns an unmodifiable map of the current system environment variables.

Download Code

2. Using System.getenv(String) function

To get a specific environment variable, you can directly call the overloaded version of the getenv() function, which accepts the environment variable’s name and returns the value of that variable from the system environment.

Download Code

 
This returns null if the specified variable is not defined in the system environment. To return a default value instead of the null value, you can use the Elvis operator.

Download Code

That’s all about reading an environment variable in Kotlin.