fun XMLStreamWriter.writeStuff(action: XMLStreamWriter.() -> Unit)
how does Kotlin know where it takes the this from?
m
Mranders
11/23/2020, 12:10 PM
You haven't included the body of
writeStuff
, 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:
Copy code
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 {
}
}