Problem
This question is motivated by trying to find a solution for this question.
Assume that you would like to construct a hierarchical structure by using the following syntax:
root {
subA {
subB("b1.1")
subB("b1.2")
}
}
The construction DSL should be type-safe, that is, it should not be possible to nest a subB
directly in root
, or to nest a subA
in another subA
. Hence, my idea is to have a method root
that returns an object defining a method subA
, where the latter in turn returns an object defining subB
.
What I would now like to have is that the block of code passed to root
, that is,
subA {
subB("b1.1")
subB("b1.2")
}
is executed such that the invocation of subB
is bound to the object created by root
. Basically like this
root { r: Root =>
r.subA { sa: SubA =>
sa.subB("b1.1")
sa.subB("b1.2")
}
}
but without having to make the receivers r
and sa
explicit.
Question: Is rebinding receivers, especially the implicit this
-receiver, inside a block of code possible in Scala - maybe using macros?
Other approaches
This article describes a similarly-looking construction DSL for XML trees. Their implementation is based on the Dynamic
feature and the resulting DSL syntax looks like this:
xml html {
xml head {
xml title "Search Links"
}
}
However, this approach requires explicit receivers (here the object xml
), and more severely, I don't think that it is type-safe in the sense that it would statically prevent you from nesting an html
node inside a title
node.