August Lilleaas
09/08/2022, 7:23 AMrespondHtml(status) { with(template) { apply() } } . The use of with here seems to be used to make sure that apply() refers to the method that’s defined as a method on HTML<T> that template implements. If you write template.apply() it resolves to the built in scope function apply . What is it about the use of with that makes Kotlin invoke the apply method on HTML<T> rather than the scope function?Big Chungus
09/08/2022, 11:59 AMAugust Lilleaas
09/08/2022, 12:09 PMBig Chungus
09/08/2022, 12:13 PMAugust Lilleaas
09/08/2022, 12:14 PMthis.apply inside the with block makes apply refer to the extension functionAugust Lilleaas
09/08/2022, 12:14 PMBig Chungus
09/08/2022, 12:14 PMAugust Lilleaas
09/08/2022, 12:15 PMapply that’s defined on a generic type actually, so it’s available for everythingBig Chungus
09/08/2022, 12:16 PMAugust Lilleaas
09/08/2022, 12:16 PMAugust Lilleaas
09/08/2022, 12:17 PMAugust Lilleaas
09/08/2022, 12:18 PMCalling such a function is special because the receiver parameter is not supplied as an argument of the call, but as the receiver of the call, be it implicit or explicit. This parameter is available inside the scope of the function as the implicit receiver or-expression, while nested scopes may introduce additional receivers that take precedence over this one.this
August Lilleaas
09/08/2022, 12:18 PMAugust Lilleaas
09/08/2022, 12:20 PMThe implicit receiver having the highest priority is also called the default implicit receiver. The default implicit receiver is available in a scope as.this
Big Chungus
09/08/2022, 12:22 PMclass Type {
fun String.doStuff() = println("Using dispatch receiver")
}
fun String.doStuff() = println("Using extension receiver")
fun main() {
val type = Type()
// Calls top-level extension function
"HI".doStuff()
// Calls a method from Type class
with(type) {
"HI".doStuff()
}
}August Lilleaas
09/08/2022, 12:47 PMTemplate<T> the apply function is defined as an extension function on T