Kotlin-限制扩展方法范围 [英] Kotlin - Restrict extension method scope

查看:611
本文介绍了Kotlin-限制扩展方法范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法限制DSL中的扩展方法?

Is there a way to restrict extension methods in DSLs?

说我有一个这样的类结构:

Say I have a class structure like this:

class Outer {
    fun middle(op: Middle.() -> Unit): Middle {
        val middle = Middle()
        middle.op()
        return middle
    }
}

class Middle {
    fun inner(op: Inner.() -> Unit): Inner {
        val inner = Inner()
        inner.op()
        return inner
    }
}

class Inner

fun outer(op: Outer.() -> Unit): Outer {
    val outer = Outer()
    outer.op()
    return outer
}

然后我可以像这样创建通话:

I can then create a call like so:

outer {
    middle {
        inner {
            middle { }  // Here is the problem
        }
    }
}

我的问题是标记为middle { }的调用令人困惑,因为当它看起来像是添加到Inner时,它会在Outer上添加Middle.

My problem is that the marked middle { } call is confusing, as it adds a Middle to the Outer when it looks like it is adding to the Inner.

有没有办法不允许middle { }呼叫?

Is there a way to not allow the middle { } call?

推荐答案

您可以对deprecated使用解决方法:

You can use a workaround with deprecated:

class Outer {
    fun middle(op: Middle.() -> Unit): Middle {...}

    @Deprecated("can not be used inside a Outer block", level = DeprecationLevel.ERROR)
    fun outer(op: Outer.() -> Unit): Outer = TODO()
}

class Middle {
    fun inner(op: Inner.() -> Unit): Inner {...}

    @Deprecated("can not be used inside a Middle block", level = DeprecationLevel.ERROR)
    fun middle(op: Middle.() -> Unit): Middle = TODO()
}

class Inner {
    @Deprecated("can not be used inside a Inner block", level = DeprecationLevel.ERROR)
    fun inner(op: Inner.() -> Unit): Inner = TODO()
}

现在,编译器将给您一个错误,并且IDE不会在完成时建议错误的功能:

Now the compiler will give you an error, and IDE will not suggest a wrong function in the completion:

outer {
    middle {
        inner {
            middle { }  // error
        }
    }
}

但是对于大型DSL,您实际上不应该这样做.最好以@KirillRakhman等待 https://youtrack.jetbrains.com/issue/KT-11551 建议.

编辑:在修正示例后,它变得更小了.对于一个类,只有一个虚拟函数,毕竟并没有那么多样板.

After I fixed my example, it became much smaller. With one dummy function for a class it is not that much of boilerplate after all.

这篇关于Kotlin-限制扩展方法范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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