How to get Kotlin's type safe builders to work in Scala?

情到浓时终转凉″ 提交于 2019-12-10 04:21:16

问题


Kotlin has awesome type safe builders that make possible to create dsl's like this

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

Awesomeness is that you cannot put tags in invalid places, like body inside head, auto-completion also works properly.

I'm interested if this can be achieved in Scala. How to get it?


回答1:


If you are interested in building html, then there is a library scalatags that uses similar concept. Achieving this kind of builders does not need any specific language constructs. Here is an example:

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)
}


来源:https://stackoverflow.com/questions/39631606/how-to-get-kotlins-type-safe-builders-to-work-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!