Assuming you have a DSL like below, I want to add ...
# announcements
i
Assuming you have a DSL like below, I want to add a condition to add +Person("Emily", 31) to the list, what would be the most suitable syntax?
Copy code
val v = village {
        house {
            +Person("Emily", 31)
            +Person("Hannah", 27)
            +Person("Alex", 21)
            +Person("Daniel", 17)
        }
        house {
            +Person("Joe", 48)
        }
        house()
        house {
            -Person("Sarah", 40)
            -Person("Tom", 26)
            -Person("Holly", 52)
        }
    }
g
if you have limited amounnt of those
Person
object types, I would rather create a function: addPerson(“Emily”, 31) removePerson(…)
i
I want to know what would be the best way to add person based on a condition
Copy code
if(conditon){addPerson(...)}
or
Copy code
addPerson(name:String, age:Int, predicate:()->Boolean)
or
Copy code
addPerson(...).onlyIf{ condition }
or any other suggestions
e
if (condition) addPerson()
is probably the way to go
2
m
well, inside a
house { }
lambda you can write whatever code you like, so using an
if
seems the simplest way to do it for me. This said, I’m not quite sure about your use case, since a Kotlin DSL is usually employed for building objects declaratively, where you have all your data explicit, so I don’t see a particular application of such a pattern here
👍 1
i
Here it's just an example, I want to add some elements to a list, in some cases the element should be added only if condition is true.
I know that the if(){} is the simplest way but I foud it break the readability of the dsl
@zsmb what do you think?
g
I think if/else is completely fine for readability. After all if you have conditional logic in dsl, just use standard condition constructions of the language Approach with
onlyIf
is not scalable, soon you will need some onlyIfOrElse etc
👍 1
z
Wow, I did not expect to be pinged about this, but I'm glad someone is finding my sample code useful 😮 For the question at hand: I would definitely just use an
if
statement (or a
for
loop, for example) inside a DSL if I needed one. I haven't seen a DSL solution for an easily readable conditional statement yet that would be better than that.
👍 2
i
Thanks for all