77

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.

0

4 Answers 4

123

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"
Sign up to request clarification or add additional context in comments.

Comments

29

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.

2 Comments

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.
Java's system class returns a String which in fact may be null
9

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 previous versions)

Comments

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)

2 Comments

Yeah, how do we use envs with that? No doc?
@PedroD The keys in the example, are built from various sources, with env vars probably having priority in case of conflicts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.