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

标签 scala kotlin dsl type-safety

Kotlin 有很棒的 type safe builders这使得创建这样的 dsl 成为可能

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

很棒的是你不能把标签放在无效的地方,比如 body 里面的头,自动完成也能正常工作。

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

最佳答案

如果你对构建 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)
}

关于scala - 如何让 Kotlin 的类型安全构建器在 Scala 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39631606/

相关文章:

scala - 分析抽象数据

android-studio - 如何将默认类型的新 kotlin 文件设置为类?

android - 在 Android Studio 中将外部库作为文件添加导致依赖性错误

java - 如何获取camel中的xml节点数

scala - Spark 数据框修剪列并转换

scala - "No default Typeable for parametrized type"使用 Shapeless 2.1.0-RC2

haskell - 计算类型索引的自由 monad 的细节

eclipse - 将语言文本转换为模型

generics - 在 Scala 参数化(泛型)类型错误中使用 Guava 的简单缓存管理器

android - 如何在 Kotlin for Android 上使用 "setTextColor(hexaValue)",