How to read an environment variable in Kotlin?
Asked Answered
B

4

70

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.

Burck answered 2/6, 2017 at 3:55 Comment(0)
P
112

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

val envVar: String = System.getenv("varname") ?: "default_value"
Piled answered 4/1, 2018 at 23:2 Comment(0)
M
28

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.

Membranous answered 2/6, 2017 at 4:10 Comment(2)
There's nothing wrong with "leveraging Java's System class". Kotlin has a strong emphasis on Java interop and when you're targeting the JVM, it's expected to use Java APIs.Crutch
Java's system class returns a String which in fact may be nullSalvia
G
7

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)

Grice answered 7/7, 2017 at 7:48 Comment(0)
G
3

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)

Gingersnap answered 2/6, 2017 at 4:4 Comment(2)
Yeah, how do we use envs with that? No doc?Prudence
@Prudence The keys in the example, are built from various sources, with env vars probably having priority in case of conflicts.Cryostat

© 2022 - 2024 — McMap. All rights reserved.