How to read an environment variable in Kotlin?

Environment VariablesKotlin

Environment Variables Problem Overview


I'd like to get a certain value from an environment variable in my Kotlin app, but I can't find anything about reading environment variables in the core libraries documentation.

I'd expect it to be under kotlin.system but there's really not that much there.

Environment Variables Solutions


Solution 1 - Environment Variables

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"

Solution 2 - Environment Variables

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.

Solution 3 - Environment Variables

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)

Solution 4 - Environment Variables

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBjornicusView Question on Stackoverflow
Solution 1 - Environment VariablesPatrick BoosView Answer on Stackoverflow
Solution 2 - Environment VariablesMarcin PorwitView Answer on Stackoverflow
Solution 3 - Environment VariablessusideView Answer on Stackoverflow
Solution 4 - Environment VariablesLF00View Answer on Stackoverflow