Im investigating Kotlin DSLs following these examples:-
https://github.com/zsmb13/VillageDSL
Im am interested in how to enforce usage rules on all attributes exposed by the DSL.
Taking the following example:-
val v = village {
house {
person {
name = "Emily"
age = 31
}
person {
name = "Jane"
age = 19
}
}
}
I would like to enforce a rule which stops users of the DSL being able to enter duplicate attributes as shown below
val v = village {
house {
person {
name = "Emily"
name = "Elizabeth"
age = 31
}
person {
name = "Jane"
age = 19
age = 56
}
}
}
I've tried with Kotlin contracts e.g.
contract { callsInPlace(block, EXACTLY_ONCE) }
However these are only allowed in top level functions and I could not see how to employ a contract when using following the Builder pattern in DSLs, e.g.
@SimpleDsl1
class PersonBuilder(initialName: String, initialAge: Int) {
var name: String = initialName
var age: Int = initialAge
fun build(): Person {
return Person(name, age)
}
}
Is it possible to achieve my desired effect of enforcing the setting of each attribute only one per person?