kotlin.函数文字与接收器– Quick Introduction

kotlin.功能文字与接收器 - DSL的基础和许多库函数

今天我想快速介绍Kotlin 带接收器的功能文字。这个概念是什么 kotlin. 非常适合设计 域特定语言 as we know it from Groovy for example. Also, Kotlin's standard library includes many functions which many of you have already used or at least seen probably: apply and with are the most prominent ones.


kotlin,除了Java,还有 恰当的 功能类型,这意味着变量可以是例如类型“函数 接受 an Int and returning a String": (Int)->String. These function types can be used as parameters to other functions, which are in turn called "higher order functions":

fun myHigherOrderFun(functionArg: (Int)->String) = functionArg(5)

As you can see myHigherOrderFunhas a parameter of a function type, which it can call in its method body. If we now want to use this higher order function, we can make use of lambdas, also referred to as "function literal":

println ( myHigherOrderFun { "The Number is $it" })
>> prints "The Number is 5"


正如我们所看到的那样,功能文字可以用作其他函数的参数,这是一个令人敬畏的功能。尽管如此,Kotlin也进一步走得进一步并支持“与接收器功能文字”的概念。这使我们能够呼叫方法 接收者 在没有任何特定的限定符的身体中的功能文字。这与之非常相似 扩展功能,也可以在扩展内部访问接收器对象的成员。让我们看看,有什么功能文字看起来像:

var greet: String.() -> Unit = { println("Hello $this") }

This one defines a variable of type String.() -> Unit, which is basically a function type () -> Unit with String as the 接收者. All methods of this receiver can, therefore, be called in the method body. In this example, this is simply used to print the String. The function can be called like so:

>> prints "Hello Hadi"


在行动 - 范围函数

正如我开始的那样,Kotlin的 标准库包含使用此概念的方法, one of which is apply. This one is defined as follows:

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

正如我们很容易看,这是一个 扩展功能 关于一切都在字面上,它期待一个 功能文字与通用接收器 of type T, which is run before the receiver is returned to the caller. This little function is actually fantastic as it provides a way to build certain objects very concisely and easily.

println(StringBuilder("Hello ")
        .apply {
            append("! ")
            append("How are you doing?")
>> prints "Hello Kotliner! How are you doing?"

In this example, a StringBuilder is created and then the apply method is called on it. As we've seen before, it's possible to call any method of our receiver StringBuilder like append in the above code. Since apply returns the receiver after it completes, a call of toString on the StringBuilder can immediately be performed and the text is printed to the console.

希望这可以帮助!我真的很喜欢这个功能,因为它给我们这么多的可能性。可能是Kotlin最重要的一个 - 如果您想了解创建DSL,请查看 这里。我自己在我的代码中发现了这么多的景点,我可以使用这些接收器感知功能来简化很多;今天看看你的 -

最后,如果你想阅读Kotlin的美丽功能,我推荐这本书 kotlin在行动中 to you!


11 thoughts on “kotlin.函数文字与接收器– Quick Introduction


您的电子邮件地址不会被公开。 必需的地方已做标记 *