Created
December 20, 2009 10:03
-
-
Save retronym/260426 to your computer and use it in GitHub Desktop.
Emulating Groovy's Builder in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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