ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
### `with` 一个**非扩展函数**:**上下文对象**作为参数传递,但是在 lambda 表达式内部,它可以作为接收者(`this`)使用。 **返回值**是 lambda 表达式结果。 适用场景:**一个对象的一组函数调用**:`with` 我们**建议使用 `with` 来调用上下文对象上的函数,而不使用 lambda 表达式结果**。 在代码中,`with` 可以理解为“**对于这个对象,执行以下操作。**” ```kotlin fun main() { //sampleStart val numbers = mutableListOf("one", "two", "three") with(numbers) { println("'with' is called with argument $this") println("It contains $size elements") } //sampleEnd } ``` **`with` 的另一个使用场景是引入一个辅助对象,其属性或函数将用于计算一个值**。 ```kotlin fun main() { //sampleStart val numbers = mutableListOf("one", "two", "three") val firstAndLast = with(numbers) { "The first element is ${first()}," + " the last element is ${last()}" } println(firstAndLast) //sampleEnd } ```