Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read an environment variable in Kotlin?

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.

like image 254
Bjornicus Avatar asked Jun 02 '17 03:06

Bjornicus


People also ask

How do you define a variable in Kotlin?

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.

What is kotlin string interpolation?

String interpolation in Kotlin allows us to easily concatenate constant strings and variables to build another string elegantly.

What is system Getenv in Java?

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).


2 Answers

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" 
like image 83
Patrick Boos Avatar answered Oct 22 '22 21:10

Patrick Boos


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.

like image 31
Marcin Porwit Avatar answered Oct 22 '22 21:10

Marcin Porwit