<ClassName>.() 在 Kotlin 中是什么意思? [英] What does <ClassName>.() mean in Kotlin?

查看:15
本文介绍了<ClassName>.() 在 Kotlin 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定这是什么意思,但我在 kotlin html 代码库中遇到了这种语法.SCRIPT.() 是什么意思?

Not sure what this means but I came across this syntax in the kotlin html codebase. What does SCRIPT.() mean?

https://github.com/Kotlin/kotlinx.html/blob/master/shared/src/main/kotlin/generated/gen-tag-unions.kt#L143

fun FlowOrPhrasingOrMetaDataContent.script(type : String? = null, src : String? = null, block : SCRIPT.() -> Unit = {}) : Unit = SCRIPT(attributesMapOf("type", type,"src", src), consumer).visit(block)

SCRIPT 是一个类 - https://github.com/Kotlin/kotlinx.html/blob/master/shared/src/main/kotlin/generated/gen-tags-s.kt.

SCRIPT is a class - https://github.com/Kotlin/kotlinx.html/blob/master/shared/src/main/kotlin/generated/gen-tags-s.kt.

或者更一般地说,.() 在 Kotlin 中是什么意思?

Or more generally, what does <ClassName>.() mean in Kotlin?

推荐答案

快速解答

block: SCRIPT.() -> Unit = {}

这表示带有接收器的函数文字".它是一个函数参数,函数类型 () ->UnitSCRIPT 作为接收者.

This represents a "function literal with receiver". It’s a function parameter with a function type () -> Unit and SCRIPT as it’s receiver.

Kotlin 支持带有接收器的函数字面量"的概念.它允许访问 lambda 主体中接收者的可见方法和属性,无需任何特定限定符.这非常类似于扩展函数,在扩展函数中也可以访问扩展内部接收者对象的可见成员.

Kotlin supports the concept of "function literals with receivers". It enables the access on visible methods and properties of a receiver of a lambda in its body without any specific qualifiers. This is very similar to extension functions in which it’s also possible to access visible members of the receiver object inside the extension.

一个简单的例子,也是 Kotlin 标准库中最伟大的函数之一,是apply:

A simple example, also one of the greatest functions in the Kotlin standard library, isapply:

public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }

正如你所看到的,这样一个带有接收器的函数文字在这里被当作参数block.这个块被简单地执行并返回接收器(它是 T 的一个实例).实际操作如下:

As you can see, such a function literal with receiver is taken as the argument block here. This block is simply executed and the receiver (which is an instance of T) is returned. In action this looks as follows:

val foo: Bar = Bar().apply {
    color = RED
    text = "Foo"
}

我们实例化一个Bar 的对象,并在其上调用apply.Bar 的实例成为接收者".在 {}(lambda 表达式)中作为参数传递的 block 不需要使用额外的限定符来访问和修改显示的可见属性 colortext.

We instantiate an object of Bar and call apply on it. The instance of Bar becomes the "receiver". The block, passed as an argument in {}(lambda expression) does not need to use additional qualifiers to access and modify the shown visible properties color and text.

带有接收器的 lambdas 的概念也是使用 Kotlin 编写 DSL 的最重要的特性.

The concept of lambdas with receiver is also the most important feature for writing DSLs with Kotlin.

这篇关于&lt;ClassName&gt;.() 在 Kotlin 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆