@ DSLMarker不限制DSL的范围

问题描述 投票:0回答:1

我正在为HTML构建Kotlin DSL,以满足我的非常具体的要求(因此不使用kotlinx.html)

        DIV(classes = "div1") {
            +"text1"
            a(href = "#0") {
                +"text2"
                div(classes = "div2") {
                    +"text3"
                    href = "#1"
                }
                div(classes = "div3") {
                    +"text4"
                    href = "#2"
                }
            }
            hr(classes = "hr1")
            span(classes = "span1") {
                +"text5"
            }
        }

在上面的示例中,我可以在href的任何子元素中调用a,而不必执行[email protected] = ""。如何限制范围,以使this在此示例中仅为DIV类型,并且由于href没有DIV属性而在调用href时引发编译器错误?

这里是DIV类的简化版本https://github.com/persephone-unframework/dsl/blob/master/src/main/kotlin/io/persephone/dsl/element/DIV.kt

@DslMarker
annotation class DivMarker

@DivMarker
class DIV(
    classes: String? = null,
    ....
    init: (DIV.() -> Unit)? = null
) : Tag(
    tagName = "div",
    selfClosing = false
) {

    fun a(
        classes: String? = null,
        ....
        init: (A.() -> Unit)? = null
    ) = A().let {

        this.children.add(it)
        ....
        init?.invoke(it)
        it
    }

    ....

}

类似地,A类也被标记为:https://github.com/persephone-unframework/dsl/blob/master/src/main/kotlin/io/persephone/dsl/element/A.kt

@DslMarker
annotation class AMarker

@AMarker
class A(
    href: String? = null,
    ...
    init: (A.() -> Unit)? = null
) : Tag(
    tagName = "a",
    selfClosing = false
) {

    fun div(
        classes: String? = null,
        init: (DIV.() -> Unit)? = null
    ) = DIV().let {

        this.children.add(it)

        ....

        init?.invoke(it)
        it
    }

    ....
}

任何想法,为什么@DslMarker注释在这种情况下都不会限制范围,我该如何解决?

kotlin dsl
1个回答
0
投票

似乎是在注释基类,在这种情况下是Tag,这个技巧可能意味着所有其他注释都没有用吗?

@DslMarker
annotation class TagMarker

@TagMarker
abstract class Tag(val tagName: String, var selfClosing: Boolean = false): Element {

    val children = arrayListOf<Element>()
    val attributes = hashMapOf<String, String>()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.