Bernhard
11/23/2020, 11:39 AMfun XMLStreamWriter.writeStuff(action: XMLStreamWriter.() -> Unit)
how does Kotlin know where it takes the this from?Mranders
11/23/2020, 12:10 PMwriteStuff, so I'm assuming it doesn't do something out of the ordinary.
The writeStuff function is defined as an extension function on XMLStreamWriter. This means that the function can only be invoked on some instance of XMLStreamWriter. When invoking it, then this will be that instance. Example:
fun foo(writer: XMLStreamWriter) {
writer.writeStuff {
//These will be invoked on "writer", because this is the instance you are invoking the extension on
writeStartDocument()
writeComment("Hello world")
writeEndDocument()
}
//This does not compile, because "writeStuff" needs an instance of XMLStreamWriter to be invoked
writeStuff {
}
}Bernhard
11/23/2020, 1:48 PM