Read an environment variable in Kotlin
This post will discuss how to read the value of an environment variable in Kotlin.
1. Using System.getenv() function
The standard solution is to use the System.getenv(), which returns an unmodifiable map of the current system environment variables.
|
1 2 3 4 5 |
fun main() { val env: MutableMap<String, String> = System.getenv() println("Path: ${env["OS"]}") // Path: Windows_NT } |
2. Using System.getenv(String) function
To get a specific environment variable, you can directly call the overloaded version of the getenv() function, which accepts the environment variable’s name and returns the value of that variable from the system environment.
|
1 2 3 4 5 |
fun main() { val path = System.getenv("OS") println(path) // Windows_NT } |
This returns null if the specified variable is not defined in the system environment. To return a default value instead of the null value, you can use the Elvis operator.
|
1 2 3 4 5 |
fun main() { val path = System.getenv("OS") ?: "Not Found" println(path) // Windows_NT } |
That’s all about reading an environment variable in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)