Skip to content

Instantly share code, notes, and snippets.

@retronym
Created December 20, 2009 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retronym/260426 to your computer and use it in GitHub Desktop.
Save retronym/260426 to your computer and use it in GitHub Desktop.
Emulating Groovy's Builder in Scala
class HtmlBuilder {
var html: NodeSeq = NodeSeq.Empty
def b(f: (HtmlBuilder) => Unit): Unit = appendNodes(<b>{val b1 = new HtmlBuilder; f(b1); b1.html}</b>)
def a(href: String)(f: (HtmlBuilder) => Unit): Unit = appendNodes(<a href={href}>{val b1 = new HtmlBuilder; f(b1); b1.html}</a>)
def text(text: String): Unit = appendNodes(Text(text))
def appendNodes(nodes: xml.Node*) = html = html ++ nodes
}
implicit val builder: HtmlBuilder = new HtmlBuilder
import builder._
a(href = "http://scala-lang.org") { builder => import builder._
b { builder => import builder._
text("Scala Lang Website")
}
}
assert(builder.html.toString == """<a href="http://scala-lang.org"><b>Scala Lang Website</b></a>""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment