继上一篇文章介绍了项目中所使用的Kotlin特性,本文继续整理当前项目所用到的特性。
一.apply 函数 和 run 函数
with、apply、run函数都是Kotlin标准库中的函数。with在第一篇文章中已经介绍过。
1.1 apply函数
apply函数是指在函数块内可以通过 this 指代该对象,返回值为该对象自己。在链式调用中,可以考虑使用它来不破坏链式。
/**
* Calls the specified function [block] with `this` value as its receiver and returns `this` value.
*/
@kotlin.internal.InlineOnly
public inline fun T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
举个例子:
/**
* Created by tony on 2018/4/26.
*/
object Test {
@JvmStatic
fun main(args: Array) {
val result ="Hello".apply {
println(this+" World")
this+" World"
}
println(result)
}
}
执行结果:
Hello World
Hello
第一个字符串是在闭包中打印的,第二个字符串是result的结果,它仍然是“Hello”。
1.2 run函数
run函数类似于apply函数,但是run函数返回的是最后一行的值。
/**
* Calls the specified function [block] with `this` value as its receiver and returns its result.
*/
@kotlin.internal.InlineOnly
public inline fun T.run(block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}