What's the most idiomatic Kotlin way of creating a...
# getting-started
l
What's the most idiomatic Kotlin way of creating a database config object like the following? Do I use a
data class
, a function returning a
DbConfig
class instantiated via primary constructor, a class with an
init
block, ...?
d
A data class is a good way to hold the data. How to get an instance of it depends on what framework(s) you're using.
If you're using Spring, for instance, you could annotate it with
@ConstructorBinding
and
@ConfigurationProperties
.
It looks like you're using dotenv(), which I'm not familiar with. I would consider something like this:
Copy code
data class DbConfig(
    val port: Int,
    val name: String,
    val user: String,
    val password: String,
)

fun Dotenv.loadDbConfg() =
   DbConfig(
      port = get("POSTGRES_PORT").toInt(),
      name = get("POSTGRES_DB"),
      user = get("POSTGRES_USER"),
      password = get("POSTGRES_PASSWORD"),
   )
Then you can use
val dbConfig = dotenv().loadDbConfig()
l
Ah, I see, an extension method, that's neat. Thanks for the tip, I'll use that!
d
There's always #hoplite, if you want a full featured solution.