How to read the environment variable in Kotlin?

I would like to get a specific value from an environment variable in my Kotlin application, but I cannot find anything about reading environment variables in core libraries .

I expect it to be under kotlin.system , but there really isn’t much there.

+6
source share
4 answers

You can use the kotlin Konfig extension

Konfig - Type of Secure Configuration API for Kotlin

Konfig , API , - , , , , ..

+1

:

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

, , , Java System, Kotlin's.

+10

It is very simple to get the environment value if it exists or the default value using the elvis operator in kotlin:

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

My favorite airliner:

val myEnv = if (System.getenv("MY_ENV").isNullOrEmpty()) "default_value" else System.getenv("MY_ENV")
+2
source

All Articles