I'm currently in the process of learning about Kotlin DSLs.
I've been playing around with it for a while now but I'm unable to solve my use case. I have a simple DSL, and I don't care too much of the types it has as long as I can achieve a syntax like this:
private fun getObj(): SET {
return SET {
ITEM {
A = null
B = "Hello world"
C
// D - exists in DSL but omitted here
}
}
}
In the background, I now want to distinguish between certain values set in the ITEM
block. B
is easy, it is simply the value, but it becomes hard for A
and C
. Somehow I'm not able to differentiate between null
and no value
set. Currently my builder looks like this, but I'm open to changing it to achieve the syntax above:
class ITEMBuilder {
var A: String? = null
var B: String? = null
var C: String? = null
var D: String? = null
fun build() = ITEM(
ItemValue(A),
ItemValue(B),
ItemValue(C),
ItemValue(D)
)
}
class ItemValue(val include: Boolean? = false, val value: String? = null) {
constructor(value: String? = null): this(null != value, value)
}
When I have my final object, I want to be able to tell 4 different stages for each field under ITEM:
- value set
- null set
- no value set
- field omitted
I tried different types, but had no luck since most things impact the syntax. I also tried to change the getter/setters in the builder, to maybe catch the update there and have an additional internal property that gets updated - but neither get
or set
are called for null/no value. Also tried to change the fields to functions but then I have ugly parenthesis ()
in the DSL syntax.
Would be great if somebody could help me figure this out.
Thanks in advance!