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
Daniel Pitts
01/18/2024, 3:46 PM
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.
Daniel Pitts
01/18/2024, 3:47 PM
If you're using Spring, for instance, you could annotate it with
@ConstructorBinding
and
@ConfigurationProperties
.
Daniel Pitts
01/18/2024, 3:53 PM
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"),
)
Daniel Pitts
01/18/2024, 3:57 PM
Then you can use
val dbConfig = dotenv().loadDbConfig()
l
Linus
01/18/2024, 4:54 PM
Ah, I see, an extension method, that's neat. Thanks for the tip, I'll use that!
d
dave08
01/19/2024, 7:59 AM
There's always #hoplite, if you want a full featured solution.