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

查看:83
本文介绍了< 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?

SCRIPT是一个类- https://github.com/Kotlin/kotlinx.html/blob/master/shared/src/main/kotlin/generation/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.

或更笼统地说,<ClassName>.()在科特林语中是什么意思?

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.

apply是一个简单的示例,也是Kotlin标准库中最大的功能之一:

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.

带有接收器的lambda的概念也是用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天全站免登陆