如何让Kotlin的类型安全构建器在Scala中工作?

Yar*_*lav 6 dsl scala type-safety kotlin

Kotlin拥有令人敬畏的类型安全构建器,可以创建像这样的dsl

html {
  head {
    title("The title")
    body {} // compile error
  }
  body {} // fine
}
Run Code Online (Sandbox Code Playgroud)

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

我很感兴趣,如果这可以在Scala中实现.怎么弄?

Yev*_*nyk 3

如果您对构建 html 感兴趣,那么有一个使用类似概念的库scalatags 。实现这种构建器不需要任何特定的语言结构。这是一个例子:

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)
}
Run Code Online (Sandbox Code Playgroud)