今天来学习一下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,最后我们把张三改名为王五,年龄25,看一下实现:
var person = Person("张三", "23")
with(person) {
name = "王五"
age = "25"
}
println(person)
打印出来的结果:
Person(name=王五, age=25)
由此,我们分析一下,在with函数中,我们把person传入,然后在with的第二个函数参数中,修改这个传入的person的值,而且我们并没有在name或者age前加上前缀,在这里,可以理解为,我们是写的this.name,只是把this省略了。(只是先粗略这么理解)
文章若有错漏,还请指正!