How do I read an environment variable in Kotlin?

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

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.

回答1:

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"


回答2:

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.



回答3:

My favorite one-liner is:

val myEnv = if (System.getenv("MY_ENV").isNullOrEmpty()) "default_value" else System.getenv("MY_ENV")


回答4:

You can use the kotlin extension Konfig

Konfig - A Type Safe Configuration API for Kotlin

Konfig provides an extensible, type-safe API for configuration properties gathered from multiple sources ― built in resources, system properties, property files, environment variables, command-line arguments, etc.

For example: Key("http.port", intType)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!