Playing about with a DSL in Scala, so lets say I have something like this:
house {
floor {
bedroom("kids)
bedroom("master")
}
floor {
kitchen()
}
}
Now what I want is at each nested block it to have a reference or be referencing functions on the enclosing block. Eg so the effect is that floor is added to the house, bedroom to the floor etc.
Currently I do this in a horrible fashion of having a global stack that gets updated at each nested level to keep track of the current “context”. Also my current version is not typesafe in that I can add a bedroom to a house.
Another previous revision was
house {
floor {
bedroom("kids) +
bedroom("master")
} +
floor {
kitchen()
}
}
Where each block returned a List of widgets (the + was using an implicit to turn a generic “thing” into a “thing list” so that the next “thing” can be added). The returned list of widgets was then added once the block returned. But I do not like the forced use of + as it gets ugly on many pages worth.
Anyway to meld the two ?
Do you really need each block to have a reference to the enclosing block? Or was it just so that you could add the nested block to the parent block? In this case you could simply pass nested blocks to the enclosing block, so to speak:
Using the following definitions:
Otherwise, another solution is to rely heavily on anonymous classes (which unfortunately requires to use the
newkeyword everywhere):Using the following definitions: