Kotlin 很棒类型安全的构建者 https://kotlinlang.org/docs/reference/type-safe-builders.html这使得创建像这样的 dsl 成为可能
html {
head {
title("The title")
body {} // compile error
}
body {} // fine
}
令人敬畏的是,您不能将标签放在无效的位置,例如头部内的正文,自动完成功能也可以正常工作。
我很感兴趣这是否可以在 Scala 中实现。如何获得?
如果您对构建 html 感兴趣,那么这里有一个库阶梯 https://github.com/lihaoyi/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)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)