What does <ClassName> mean. () In Kotlin?
Not sure what this means, but I came across this syntax in kotlin html codebase. What does SCRIPT. () Mean?
fun FlowOrPhrasingOrMetaDataContent.script(type : String? = null, src : String? = null, block : SCRIPT.() -> Unit = {}) : Unit = SCRIPT(attributesMapOf("type", type,"src", src), consumer).visit(block) SCRIPT is a class - https://github.com/Kotlin/kotlinx.html/blob/master/shared/src/main/kotlin/generated/gen-tags-s.kt .
Or, in general, what does <ClassName>.() in Kotlin?
Quick response
block: SCRIPT.() -> Unit = {} This is a " function literal with a receiver . " Its function parameter with function type () -> Unit and SCRIPT as its receiver .
Function Literals / Lambda with receiver
Kotlin supports the concept of "functional literals with receivers." It allows you to access the visible methods and properties of the lambda receiver in your body without any specific qualifiers. This is very similar to the extension function , in which you can also access the visible members of the recipient object inside the extension.
A simple example, also one of the greatest functions of the Kotlin standard library, is apply :
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this } As you can see, such a function literal with a receiver is accepted as a block argument here. This block is just executed, and the receiver (which is an instance of T ) is returned. In action, it looks like this:
val foo: Bar = Bar().apply { color = RED text = "Foo" } We create a Bar object and call apply on it. An instance of Bar becomes a "receiver". block , passed as an argument to {} (lambda expression), you do not need to use additional qualifiers to access and change the displayed visible color and text properties.
The lambda concept with receiver is also the most important feature for writing DSL with Kotlin.