Sling Academy
Home/Kotlin/Accessing Environment Variables in Kotlin

Accessing Environment Variables in Kotlin

Last updated: November 30, 2024

In Kotlin, you can easily access environment variables which are key-value pairs available to a program that inform it about the environment it is running in. This can be useful in scenarios like accessing secret keys, API tokens, database URLs, etc., without hardcoding these into your codebase. In this article, we'll explore how to read environment variables in Kotlin with some code examples.

Reading Environment Variables

Kotlin interoperates seamlessly with Java, which exposes environment variables through the System class. You can use the following approach in a Kotlin program to retrieve environment variables:

// Example of accessing an environment variable in Kotlin
fun main() {
    val dbUser = System.getenv("DB_USER")
    val dbPass = System.getenv("DB_PASS")

    if (dbUser != null && dbPass != null) {
        println("Database User: $dbUser")
        println("Database Password: $dbPass")
    } else {
        println("Environment variables are not set")
    }
}

In this example, the function System.getenv() is used to retrieve the values of the environment variables DB_USER and DB_PASS. If these environment variables are not set, it will print a message accordingly.

Providing Default Values

It’s often useful to provide a default value if an environment variable is not set. You can achieve this using the ?: operator in Kotlin:

// Example with default values
fun main() {
    val dbUser = System.getenv("DB_USER") ?: "defaultUser"
    val dbPass = System.getenv("DB_PASS") ?: "defaultPassword"

    println("Database User: $dbUser")
    println("Database Password: $dbPass")
}

Here, if the environment variables DB_USER or DB_PASS are not set, the program uses defaultUser and defaultPassword as their default values, respectively.

Error Handling

When environment variables are crucial for your application’s configuration, you might want to enforce their existence and throw an error if not found:

// Example with error handling
fun main() {
    val dbUser = System.getenv("DB_USER")
      ?: throw IllegalArgumentException("DB_USER environment variable is not set")
    val dbPass = System.getenv("DB_PASS")
      ?: throw IllegalArgumentException("DB_PASS environment variable is not set")

    println("Database User: $dbUser")
    println("Database Password: $dbPass")
}

In this code, if either DB_USER or DB_PASS is not set, the program will throw an IllegalArgumentException with a descriptive error message.

Conclusion

Accessing environment variables in Kotlin is a straightforward task using the System.getenv() method, which provides you with powerful ways to configure your application at runtime without exposing sensitive information directly in your codebase. Remember to handle cases where these might not be set to ensure your application behaves predictably.

Next Article: Reading System Properties with Kotlin

Previous Article: How to Handle Hidden Files in Kotlin

Series: Kotlin - File & OS

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin