简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM