Kotlin中<ClassName>.()语法含义解析,含SCRIPT.()实例疑问
<ClassName>.() -> Unit mean in Kotlin? Great question! That <ClassName>.() -> Unit syntax you're encountering is called a function type with receiver in Kotlin, and it's the secret sauce behind many of Kotlin's most expressive domain-specific languages (DSLs)—like the one used in kotlinx.html. Let's break this down clearly, using your example code as context.
Core Concept
At its simplest, SCRIPT.() -> Unit defines a function that:
- Takes no explicit parameters
- Returns
Unit(similar tovoidin Java) - Runs in the context of a
SCRIPTclass instance—meaning inside the function,thisautomatically refers to an instance ofSCRIPT, just like it would in a member function of the class.
You can think of it as representing an extension function type: this function behaves like an extension function for SCRIPT that takes no arguments and returns nothing.
Applying It to Your kotlinx.html Example
Looking at the code you shared:
fun FlowOrPhrasingOrMetaDataContent.script( type : String? = null, src : String? = null, block : SCRIPT.() -> Unit = {} ) : Unit = SCRIPT(attributesMapOf("type", type,"src", src), consumer).visit(block)
The block parameter is a function type with receiver for SCRIPT. When the script function is called:
- A new
SCRIPTinstance is created with the provided attributes. - The
visit(block)method executes theblockfunction, passing theSCRIPTinstance as its receiver.
This lets you write clean, HTML-like code in your Kotlin DSL. For example:
// Usage in kotlinx.html body { script(src = "app.js") { // Inside this lambda, `this` is the SCRIPT instance attr("async", "true") // Call a member method of SCRIPT async = true // Or set a property directly } }
No need to explicitly reference the SCRIPT object—you can interact with it directly as if you're writing code inside the class itself.
A Simplified Standalone Example
If you want to experiment with this concept outside of kotlinx.html, here's a quick example to illustrate:
class Book(val title: String) // Define a variable with a function type with receiver val printBookInfo: Book.() -> Unit = { println("Title: $title") // `title` is from the Book instance via `this` println("Estimated pages: ${this.title.length * 10}") // Explicit `this` works too } // Use the function val dune = Book("Dune") dune.printBookInfo() // Output: // Title: Dune // Estimated pages: 40
Why This Matters
Function types with receiver are what make Kotlin DSLs feel natural and intuitive. They let you write code that mirrors the structure of the domain you're working with (like nested HTML tags) while keeping the code concise, readable, and type-safe.
内容的提问来源于stack exchange,提问作者sat

