kotlin 中 let, also, apply, run, with的用法

146 阅读1分钟

背景 :

在实际的开发过程中,除了let,其他的关键字,例如:# let, also, apply, run, with, 我是真的不理解他们的用法,今天有空,就探究一下他们的用法,这样,在别人代码时候,便于理解别人 的意图;

let

1. null check,
  • 反编译一下字节码,做一下对比 let.png

  • kotlin 在内部做了大量的优化

// 防止crash
var number: Int? = null 
number?.let {
   number = 4
}
2. return the last line.
public fun test3() {
    val x = number?.let {
        val number2 = it.plus(1)
        // 若number2 是 null,直接返回null
        // let 返回last line;
        number2
    } ?: 3
    println(" x:  $x")
}

also

1. it 关键字,可代表正在使用的对象

also.png

var i: Int = 5
public fun getSquare() = (i * i).also {
    // 执行完i*i 以后,执行also 代码块里的逻辑 i++;
    println("it value :$it")
    i = it + 1
}

apply

1. 可变对象,设置参数,需要 dot call
public fun test4() {
  val map = mutableMapOf<String, String>().apply {
      put("1", "666")
      put("2", "777")
      put("3", "888")
  }
  println("map : $map")
}

with

with.png

1. 和apply类似,但是不用dot call
fun test6_with() {
   val student = Student(16, " 小李");
   with(student) {
       age = 22
       name = "小王"
       this.drink()
   }
}

run

1 : return last line
2 : doesn’t support the it keyword.

run.png

参考