Kotlin之with、apply、run、let、also函数的区别

这几个函数非常相似,有细微区别,下面举例说明。

1、先新建一个数据类

data class User(var name : String, var age:Int) {
    fun say(msg: String?): String? = msg
}

2、在main方法中测试下
with 操作当前对象,可返回另外一个值

fun main(args: Array) {
    val user = User("wj", 25)
    val withResult = with(user) {
    name = "niuniuniu"
    age = 11
    "other value"
}
println(withResult ) //结果:other value
}

apply 操作当前对象,返回当前对象

fun main(args: Array) {
  val user = User("wj", 25)
  val applyResult = user.apply {
    name ="haha"
    age =11
  }
  println(applyResult)  //结果:User(name=haha, age=11)
}

run 操作当前对象,可以返回另外一个值

fun main(args: Array) {
  val user = User("wj", 25)
  val runResult = user.run {
    name ="run name"
    age =666
    //调用say方法,返回say方法的值
    say("say run")
  }
  println(runResult) //结果:say run
}

let 当前对象作为参数,返回另外一个对象

fun main(args: Array) {
  val user = User("wj", 25)
  val letResult = user.let {
    it.name
  }
  println(letResult ) //结果:wj
}

also 当前对象作为参数,返回当前对象

fun main(args: Array) {
  val user = User("wj", 25)
  val alsoResult = user.also {
    println("内部打印:$it")
    it.name ="new name"
  }
  println(alsoResult) 
//结果:
内部打印:User(name=wj, age=25)
User(name=new name, age=25)
}

你可能感兴趣的:(Kotlin之with、apply、run、let、also函数的区别)