
4.3.2 常用标准库的扩展函数
下面要介绍的扩展函数位于Standard.kt。
1.with
with是将某个对象作为函数的参数,在函数块内可以通过this指代该对象。在函数块内可以直接调用对象的方法或者属性。
在with函数中还包含Contract DSL,它是为编译器提供有关函数行为的附加信息,这有助于分析质量。后面其他的扩展函数也有Contract DSL,在阅读源代码时可以忽略掉。本书的第9章会专门介绍Contract。

以Android App的某个Adapter为例,在使用with之前可能会是这样的:

使用with之后,在with函数块内可以省略“content.”:

2.apply
apply函数在函数块内可以通过this指代该对象,返回值为该对象自己。在链式调用中,我们可以考虑使用它,从而不用破坏链式。

举个例子:

执行结果如下:
Hello World Hello
第一个字符串是在闭包中打印的,第二个字符串是result的结果,仍然是“Hello”。
3.run
run函数类似于apply函数,但是run函数返回的是最后一行的值。

举个例子:

执行结果如下:
Hello World Hello World
第一个字符串是在闭包中打印的,第二个字符串是result的结果,返回的是闭包中最后一行的值,所以也打印了“Hello World”。
4.let
let函数把当前对象作为闭包的it参数,返回值是函数中的最后一行,或者指定return。它看起来有点类似于run函数。
let函数跟run函数的区别是:let函数在函数内可以通过it指代该对象。

通常情况下,let函数跟“?”结合使用:

可以在obj不为null的情况下执行let函数块的代码,从而避免空指针异常的出现。
5.also
also是Kotlin 1.1新增的函数,类似于apply的功能。跟apply不同的是,also在函数块内可以通过it指代该对象,返回值为该对象自己。

举个例子:

执行结果如下:
Hello World Hello
可以看到执行结果跟apply函数的执行结果是一致的。
列举完Kotlin标准库常用的几个扩展函数之后,我们会发现它们都是高阶函数,而且还都使用了inline。图4-3总结了它们之间的关系。

图4-3 标准库常用的扩展函数