How to read an environment variable in Kotlin?

You could always go down this approach:

val envVar : String? = System.getenv("varname")

Though, to be fair, this doesn't feel particularly idiomatic, as you're leveraging Java's System class, not Kotlin's.


You can use the kotlin extension Konfig

Konfig - A Type Safe Configuration API for Kotlin

Konfig provides an extensible, type-safe API for configuration properties gathered from multiple sources — built in resources, system properties, property files, environment variables, command-line arguments, etc.

For example: Key("http.port", intType)


And if you want to handle env var which do exists but is empty:

val myEnv = (System.getenv("MY_ENV") ?: "").ifEmpty { "default_value" }

(see edit history for previos versions)


It is really easy to get a environment value if it exists or a default value by using the elvis operator in kotlin:

var envVar: String = System.getenv("varname") ?: "default_value"