Kotlin - Restrict extension method scope

后端 未结 2 828
暗喜
暗喜 2021-01-06 11:03

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


        
2条回答
  •  执笔经年
    2021-01-06 11:25

    The official way to restrict scope is DslMarker. It cannot help in some cases (when you need to annotate java sources, for example) - and here @Deprecated is used. But try DslMarker first.

    @DslMarker
    @Target(AnnotationTarget.CLASS, AnnotationTarget.TYPE)
    annotation class Scope
    
    @Scope
    class Outer {
        fun middle(op: Middle.() -> Unit): Middle { /**/ }
    }
    
    @Scope
    class Middle {
        fun inner(op: Inner.() -> Unit): Inner {/**/ }
    }
    
    class Inner
    

    Thus the last middle call is not compilable anymore.

提交回复
热议问题