I have a hierarchy of configuration elements that all implement an interface (simplified):
interface Configuration {
val elements: Long
val data: Long?
var parent: Configuration?
}
Implementations will be constructed by jackson-kotlin reading a Yaml file like this:
checks:
elements: 10
data: 1234
ports:
elements: 5
Code may do the same:
CheckConfig(elements = 10, data = 1234, portConfig = PortConfig(elements = 5))
My problem is - when I construct PortConfig
I don't know about it's parent, yet. Jackson might, but I don't know how I can take advantage of that.
The PortConfig
implementation needs its parent to fallback if the user hasn't given any data
attribute for this particular config portion.
What I currently do feels totally hacky:
inline fun <reified T: Configuration> T.updateChildLinks() {
(this::class as KClass<T>).memberProperties.forEach {
if (it.returnType.isSubtypeOf(Configuration::class.createType(nullable = true))) {
it.isAccessible = true
val config: Configuration = it.get(this) as Configuration
config.parent = this
}
}
}
And call this in each parent's init
block. Can I do better (in particular, I dislike that I have to remember to call the helper function in the init phase)?
Edited to add: Previously, I had a code-only solution that would pass data
down the chain:
CheckConfig(elements = 10, data = 1234,
portConfig = PortConfig(elements = 5, parentData = 1234))
and then have data
look-aside at parentData
, but I had trouble making this work with Jackson.