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.

import kotlin.system.Environment

fun main() {
    // To set a key/value pair, use System.setenv
    // To get a value for a key, use System.getenv
    // This will return null if the key isn't present in the environment
    System.setenv("FOO", "1")
    println("FOO: ${System.getenv("FOO")}")
    println("BAR: ${System.getenv("BAR")}")

    // Use System.getenv() to list all key/value pairs in the environment
    // This returns a Map<String, String>
    // Here we print all the keys
    println()
    System.getenv().forEach { (key, _) ->
        println(key)
    }
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is null.

FOO: 1
BAR: null

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...
FOO

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 kotlin environment-variables.kt
FOO: 1
BAR: 2
...

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.