Environment Variables in Kotlin
Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables in Kotlin.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is null.
The list of keys in the environment will depend on your particular machine.
If we set BAR
in the environment first, the running program picks that value up.
In Kotlin, we use System.setenv()
to set environment variables and System.getenv()
to retrieve them. The System.getenv()
function returns a Map<String, String>
containing all environment variables, which we can iterate over using Kotlin’s collection functions.
Note that setting environment variables programmatically with System.setenv()
is system-dependent and may not work on all platforms. It’s generally more reliable to set environment variables before running the program.