如何让Kotlin的类型安全的建设者在斯卡拉工作?

Kotlin有令人敬畏的类型安全建设者 ,可以创建这样的dsl

html { head { title("The title") body {} // compile error } body {} // fine } 

令人敬畏的是,你不能把标签放在无效的地方,像头内的身体,自动完成也能正常工作。

我很感兴趣,如果这可以在Scala中实现。 如何得到它?

如果你有兴趣建立HTML,那么有一个图书馆的标签 ,使用类似的概念。 实现这种构建者不需要任何特定的语言结构。 这里是一个例子:

 object HtmlBuilder extends App { import html._ val result = html { div { div{ a(href = "http://stackoverflow.com") } } } } sealed trait Node case class Element(name: String, attrs: Map[String, String], body: Node) extends Node case class Text(content: String) extends Node case object Empty extends Node object html { implicit val node: Node = Empty def apply(body: Node) = body def a(href: String)(implicit body: Node) = Element("a", Map("href" -> href), body) def div(body: Node) = Element("div", Map.empty, body) } object Node { implicit def strToText(str: String): Text = Text(str) }