今天来学习一下kotlin中with函数,首先看一下他的源码:
/**
* Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#with).
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return receiver.block()
}
with函数是将某对象作为函数的参数,在函数块内可以通过 this 指代该对象。返回值为函数块的最后一行或指定return表达式。可以看出with函数是接收了两个参数,分别为T类型的对象receiver和一个lambda函数块。是不是有点难于理解,没事,下面以一个实例来深入了解一下:
首先,我们定义一个数据类Person
data class Person(var name: String, var age: String)
然后,实例化一个Person,给他设置name为张三,age为23,最后我们把张三改名为王五