官方介绍:The Kotlin standard library contains several functions whose sole purpose is to execute a block of code within the context of an object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope. In this scope, you can access the object without its name. Such functions are called scope functions. There are five of them: let, run, with, apply, and also.
funmain(args: Array<String>) { var word = "我是小明" val returnValue = run { var word = "我是小红" println("run:$word") word } println("main:$word") println("returnValue:$returnValue") }
dataclassPerson ( var name: String, var age: Int = 0 ) funmain(args: Array<String>) { var person = Person("小明",25) val returnValue = with(person) { println("with:this=$this") var person = Person("小红",23) println("with:person=$person") age = 26 person } println("main:person=$person") println("main:returnValue=$returnValue") }
dataclassPerson ( var name: String, var age: Int = 0 ) funmain(args: Array<String>) { var person: Person? = null // T?.run当T为null时不调用run函数 person?.run { println("person?.run:person=$person") } person = Person("小明",25) val returnValue = person.run { println("person.run:this=$this") var person = Person("小红",23) println("person.run:person=$person") age = 26 person } println("main:person=$person") println("main:returnValue=$returnValue") }
dataclassPerson ( var name: String, var age: Int = 0 ) funmain(args: Array<String>) { var person: Person? = null person?.let { println("person?.let:person=$person") } person = Person("小明",25) val returnValue = person.let { println("person.let:it=$it") var person = Person("小红",23) println("person.let:person=$person") it.age = 26 person } println("main:person=$person") println("main:returnValue=$returnValue") }
dataclassPerson ( var name: String, var age: Int = 0 ) funmain(args: Array<String>) { var person: Person? = null person?.also { println("person?.also:person=$person") } person = Person("小明",25) val returnValue = person.also { println("person.also:it=$it") var person = Person("小红",23) println("person.also:person=$person") it.age = 26 person } println("main:person=$person") println("main:returnValue=$returnValue") }
dataclassPerson ( var name: String, var age: Int = 0 ) funmain(args: Array<String>) { var person: Person? = null person?.apply { println("person?.apply:person=$person") } person = Person("小明",25) val returnValue = person.apply { println("person.apply:this=$this") var person = Person("小红",23) println("person.apply:person=$person") age = 26 person } println("main:person=$person") println("main:returnValue=$returnValue") }
// 示例:使用apply函数进行链式调用 classPerson { var name = "" var age = 0 } funmain(args: Array<String>) { val person = Person().apply { name = "小明" }.apply { age = 25 } println("${person.name},${person.age}") } // 运行结果:小明,25