Reputation: 4669
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?
Upvotes: 6
Views: 554
Reputation: 562
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)
}
Upvotes: 3