如何让Kotlin的类型安全构建器在Scala中工作? [英] How to get Kotlin's type safe builders to work in Scala?

查看:93
本文介绍了如何让Kotlin的类型安全构建器在Scala中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin具有出色的类型安全的构建器,可以创建dsl的像这样

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.

我很感兴趣是否可以在Scala中实现.如何获得?

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

推荐答案

如果您对构建html感兴趣,那么这里有一个库 scalatags . 实现这种构建器不需要任何特定的语言构造.这是一个示例:

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

这篇关于如何让Kotlin的类型安全构建器在Scala中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆