6

I'm trying to keep this minimal, but let me know if I'm being too minimal.

Suppose you have a class hierarchy like this, designed for generating HTML (inspired by the Kotlin tutorial; semi-pseudocode follows):

class Tag {
  protected val children = arrayListOf<Tag>()
  operator fun String.unaryPlus() = children.add(Text(this))
}
class TagWithChildren : Tag() {
  fun head(init: Head.() -> Unit) = initializeTag(Head(), init)
  fun script(init: Script.() -> Unit) = initializeTag(Script(), init)
  fun <T : Tag> initializeTag(tag: T, init: T.() -> Unit): T {
    tag.init()
    children.add(tag)
    return tag
  }
}
class Head : TagWithChildren()
class Script : Tag()
class Text(val str: Text) : Tag()

Notice that Head has head and script methods while Script doesn't.

Now you can construct a template that looks like this:

head {
    script {
        +"alert('hi');"
    }
}

Which works great! However, if the block passed to script tries to call methods that aren't available on Script, it can call the method on Head instead. For example,

head {
    script {
        script {
            +"alert('hi');"
        }
    }
}

not only isn't a compile error, it's actually equivalent to

head {
    script {
    }
    script {
        +"alert('hi');"
    }
}

which is super confusing, from a template author's perspective.

Is there any way to prevent method lookups from traveling up the scope like that? I only want it to look at the innermost scope.


UPDATE 11/24/2016: Kotlin 1.1-M03 has introduced scope control, which I believe solves exactly this problem. https://blog.jetbrains.com/kotlin/2016/11/kotlin-1-1-m03-is-here/

12
  • Sorry, what is it Head < TagWithChildren in your first code snippet? Could you please post the real declarations instead, because small details matter when talking about builders and scopes.
    – voddan
    Jan 17, 2016 at 5:59
  • @voddan done...sorry about that, thought I was being generic when really I was just using Ruby subclassing syntax.
    – Max
    Jan 17, 2016 at 6:02
  • are you sure this what you have in you code? I am surprised it works at all, frankly. fun head(init: Head.() -> Unit) = children.add(Head()) - you do not use init here
    – voddan
    Jan 17, 2016 at 6:08
  • I'm leaving out a few of the less relevant details. I'm just trying to see a way if I can opt out of the scope traversal that the Kotlin compiler does.
    – Max
    Jan 17, 2016 at 6:10
  • As I said, details matter here, but that's up to you. As for now, you do not call the init methods anywhere, and i can't imagine it working without it. Maybe you meant fun head(init: Head.() -> Unit) = children.add(Head().init())
    – voddan
    Jan 17, 2016 at 6:14

2 Answers 2

3

The current behavior is intentional. Code in a lambda has access to receivers of all enclosing scopes. It is possible that a future version of Kotlin will add a modifier that will restrict a lambda with receiver to calling methods on that receiver only and not the enclosing scopes, but in the current version there's no way to change that behavior.

3
  • 1
    so, is there a way to create type-safe builders? workaround?
    – voddan
    Jan 17, 2016 at 9:13
  • 1
    Thanks @yole. This does make sense -- it's the way people expect closures to work, and in the non-builder case is generally what people want. Heck, even I want it for variable access but not method access, which is admittedly a bit arbitrary. Thanks for the confirmation.
    – Max
    Jan 17, 2016 at 16:45
  • 1
    Incidentally this behavior is basically documented on this old article on Kara I stumbled across, in the paragraph starting "Last question".
    – Max
    Jan 17, 2016 at 17:37
2

As a workaround, I can have it fail at runtime if I change the classes to look like this:

open class Tag {
  operator fun String.unaryPlus()
  // pulled up from TagWithChildren, call protected method
  fun head(init: Head.() -> Unit) = addChild(Head())
  fun script(init: Script.() -> Unit) = addChild(Head())

  // throws in Tag
  open protected fun addChild(t: Tag) = throw IllegalArgumentException()
}
class TagWithChildren : Tag() {
  // overridden to not throw in subclass
  protected override fun addChild(t: Tag) = children.add(t)
}

This way, every Tag has the builder methods (solving the scoping problem), but actually calling them may result in a runtime failure.

2
  • 1
    Another alternative workaround is to call the head and script builder methods on a particular object, i.e. either this.script/this.head (if receiver isn't passed as an argument, using apply) or tag.script/tag.head (if receiver is passed as argument, using let). Still, cumbersome.
    – Max
    Jan 17, 2016 at 16:48
  • 2
    you can deprecate the Tag.addChild method so that IDE will cross out it and remove from the complition
    – voddan
    Apr 4, 2016 at 17:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.