Typed environment config with validation errors
Kotlin
data class Config(val host: String, val port: Int, val debug: Boolean)
fun loadConfig(env: Map<String, String> = System.getenv()): Config {
val host = env["APP_HOST"]?.trim().takeUnless { it.isNullOrEmpty() } ?: "0.0.0.0"
val rawPort = env["APP_PORT"] ?: "8080"
val port = rawPort.toIntOrNull() ?: error("APP_PORT must be an integer, got $rawPort")
require(port in 1..65535) { "APP_PORT out of range: $port" }
val debug = when (env["APP_DEBUG"]?.lowercase()) {
null, "0", "false" -> false
"1", "true" -> true
else -> error("APP_DEBUG must be true/false")
}
return Config(host, port, debug)
}
val config = loadConfig(mapOf("APP_PORT" to "9090"))