I am relatively new to Kotlin and typed languages. Looking for some advice on to best implement my data models in Kiotlin.
Here is my current code:
data class Commitment(
val type: CommitmentType = CommitmentType,
val configuration: CommitmentConfiguration,
etc...
)
sealed interface CommitmentConfiguration {
val title: String get() = ""
etc...
}
data class BindingCommitmentConfiguration(
val strictMode: Boolean = false,
etc...
) : CommitmentConfiguration
enum class CommitmentType {
Binding,
NonBinding,
Legal
}
Given a Commitment
instance, what is the âcorrectâ way to infer the CommitmentConfiguration
type, from the CommitmentType
?
Currently, I am doing the following:
when(commitment.type){
Binding -> doSomething(commitment.config as BindingCommitmentConfiguration),
else {...}
}
This seems inefficient, as I have to explicitly cast the config, even though itâs type is fixed given the CommitmentType
.
I have considered using generics,
data class Commitment<T: CommitmentConfiguration>(
val type: CommitmentType = CommitmentType,
val configuration: T,
etc...
)
Would make more sense to use <T: CommitmentType>
, but I donât see how to automatically derive the configuration
type based on that.
As well as subtypes,
data class BindingCommitment(
val type: CommitmentType = CommitmentType,
val configuration: T,
etc...
) : Commitment(type, configuration)
This would result in lots of duplication of parameters and really large classes.
I understand this is a subjective question. But I am just trying to get a better understand on how this would typically be done in Kotlin.