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.
Kotlin uses two different keywords to declare variables: val and var . Use val for a variable whose value never changes. You can't reassign a value to a variable that was declared using val . Use var for a variable whose value can change.
String interpolation in Kotlin allows us to easily concatenate constant strings and variables to build another string elegantly.
getenv(String name) method gets the value of the specified environment variable. An environment variable is a system-dependent external named value. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH).
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With