Kotlin中的几个常用函数let with run also apply

330

经常会用到的几个扩展函数

1.let

用it代指自己,最后一行结果作为返回值,前面可以用?和!判空

@Test fun test(){
    val str = "test"
    val result =  str.let {
        println(it)
        "123"
    }
       println(result)
}
//输出结果
test
123

使用举例

arguments?.let {
if (it.containsKey(CHOOSE_DATE) && it.containsKey(CHOOSE_STATE)) {
        attendanceTime = it.getString(CHOOSE_DATE)
        attendanceState = it.getString(CHOOSE_STATE)
   }
}

2.with

with 需要传入对象作为参数,函数体内可直接调用该对象的属性方法,返回值为最后一行的结果,但不能同let一样使用?和!判空
@Test fun test(){
val str = "test"
val result =  with(str) {
println(length)
"123"
}
println(result)
//输出结果
4
123
}

使用举例

with(UserInfoHelper) {
    saveValue(USERNAME, username)
    saveValue(DEPARTNAME, departname)
    saveValue(TOKEN, token)
    saveValue(ORGCODE, orgcode)
}

3. run

可以看作with 和 let 的结合版 ,函数体内可以调用自身的属性方法,可用this代指自己,最后一行结果作为返回值,前面可以用?和!判空
@Test fun test(){
    val str = "test"
    val result =  str.run {
    println(length)
    "123"
    }
    println(result)
}
//输出结果
4
123

使用举例

edt_password.setText(intent?.run { getStringExtra(PASSWORD) })
atv_phone.setText(intent?.run { getStringExtra(PHONE) })

4.also

also同let函数类似,函数体内用it代指自己,区别在于返回值不同,also函数的返回值为自身
 @Test fun test(){
 val str = "test"
 val result =  str.also{
 println(it)
 }
 println(result)
 }
 //输出结果
 test
 test

使用举例


 val view = LayoutInflater.from(context).inflate(R.layout.monthly_choose_view, this, false).also {initView(it) }
 
 private fun initView(view: View) = with(view) {
     tv_last_month.setOnClickListener(this@MonthlyChoiceView)
     tv_next_month.setOnClickListener(this@MonthlyChoiceView)
     ...
 }

5.apply

apply和run类似,函数体内可以直接调用自身的属性方法,区别在于apply函数的返回值为自身
@Test fun test(){
    val str = "test"
    val result =  str.apply{
    println(length)
    println(this)
    }
    println(result)
}
//输出结果
4
test
test

使用举例

//画笔
private val mPaint by lazy {
    Paint().apply {
        isAntiAlias = true
        color = Color.RED
        style = Paint.Style.FILL
        strokeWidth = 10f
    }
}

canvas?.drawCircle(innerCircleX, innerCircleY, innerCircleRadius, mPaint.apply { color = Color.WHITE })

可以做个记录,经常会用到,区别不大,只是作用域和返回值有差别,多用用自然就明白了