1

My goal is to DRY up the repetitive parts of the definition of objects passed to a generic function in the following block of code:

renderTpl(response, "person.html", new Transformer {
  $(".person :first-child").contents = name
  $(".person :last-child").contents = age
})

I would like to DRY out the new Transformer part and be able to pass the block in the 2nd argument list of renderTpl instead:

renderTpl(response, "person.html") {
  $(".person :first-child").contents = name
  $(".person :last-child").contents = age
}

is it possible to achieve this without resorting to macros? I would post my attempts so far but to be honest I couldn't come up with anything right now.

Background: I'm using Scalate's awesome Scuery with servlets, combined with Lift's net.liftweb.util.Html5 and org.ccil.cowan.tagsoup for HTML5 parsing and rendering; the current renderTpl and loadTpl implementation can be seen here.

Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
  • I'm afraid that's simply not possible. The definition of `renderTpl` cannot introduce magically a new scope into its third argument. There was the beginning of an idea here: https://github.com/dsl-paradise/dsl-paradise (scope injection) but it's mostly abandoned. – sjrd Jun 23 '14 at 18:40
  • @sjrd: yeah, I immediately hit the same thought actually... but Scala enables quite a bit of non-obvious magic so it I thought it premature to simply abandon the idea. Do you think it would be possible with macros though? Just hypothetically — it would be an overkill to use them in most cases like that. – Erik Kaplun Jun 23 '14 at 18:45
  • I believe it's going to be a huge overkill. But you *might* be able to come up with something, although you'd still have to introduce `$` and other things like that in you top-level scope (as a global import), which is going to be a lot less nice than having `new Transformer` here and there. – sjrd Jun 24 '14 at 13:40
  • I'd have to introduce `$` even when using macros? I thought lexical scoping laws would be transcended by what macros can do. Am I thinking too much in terms of Lisp macros? – Erik Kaplun Jun 24 '14 at 13:42
  • The body of a macro still needs to typecheck before the macro is applied. So no, they cannot transcend the laws of lexical scoping. I don't too much about Lisp, but I suppose Lisp would indeed allow that because it is not statically typed. But Scala is. – sjrd Jun 24 '14 at 13:45
  • I'd have assumed typechecking is done *after* the AST transformation is applied, but if not, you're clearly right. – Erik Kaplun Jun 24 '14 at 15:28

0 Answers0