kotlin的let,run,apply,also,takeIf,takeUnless,with的区别

代码地址:

kotlin的run,let,apply,also,takeIf,takeUnless,with的使用和区别-CSDN下载
https://download.csdn.net/download/baidu_31093133/10582352

声明了一个测试用的对象

class TestBean {
    var name: String = "siry"
    var age: Int = 18
    var sex: String = "girl"

    fun setData(name: String = "lily", age: Int = 18, sex: String = "girl") {

    }
}

run函数:函数内使用this代替本对象

返回值为函数最后一行或者return指定的表达式

        var result = testBean.run {
            Log.i("LHD", "run 函数 this = " + this)//this代表当前testBean对象
//            it  run函数无法使用it但可以使用this来指代自己
            this?.age = 17
            this?.age//返回这行
        }
        Log.i("LHD", "run 的返回值 = $result")

输出结果:
run

run2

let函数:函数内使用it代替本对象

返回值为函数最后一行或者return指定的表达式

        var result2 = testBean.let {
            //let 函数可以使用it
            Log.i("LHD", "it = $it")//it代表当前testBean对象
//            Log.i("LHD", "let 函数 = " + this)//this代表Mainactivity
            it?.age = 16//这行其实是在调用setAge函数,如果这行为最后一行,则没有返回值
            it?.age//返回这行
        }
        Log.i("LHD", "let 返回值 = $result2")

输出结果:
let

apply函数:函数内使用this代替本对象,返回值为本对象

        var result3 = testBean?.apply {
            Log.i("LHD", "apply 函数 = " + this)//this代表当前testBean对象
            setData("sand", 20, "boy")
            age//即使最后一行是age,但返回的仍然是testBean对象
        }
        Log.i("LHD", "apply 返回值 = $result3")

输出结果:

apply

also函数:函数内使用it代替本对象,返回值为本对象

        var result4 = testBean.also {
            it?.age = 14
        }
        Log.i("LHD", "also 返回值 = $result4")

输出结果:
also

takeIf函数:条件为真返回对象本身否则返回null

  testBean?.age = 18
        //age = 18
        var resultTakeIf = testBean?.takeIf {
            it.age > 15//条件为真返回对象本身否则返回null
        }
        var resultTakeIf2 = testBean?.takeIf {
            it.age < 15//条件为真返回对象本身否则返回null
        }

takeUnless函数:条件为真返回null否则返回对象本身

 var resultTakeUnless = testBean?.takeUnless {
            it.age > 15//条件为真返回null否则返回对象本身
        }
        var resultTakeUnless2 = testBean?.takeUnless {
            it.age < 15//条件为真返回null否则返回对象本身
        }

输出结果:
takeIf

with函数:传入参数为对象,函数内使用this代替对象

返回值为函数最后一行或者return指定的表达式

 with(testBean) {
            this?.setData("with", 15, "boy")
            //setData()//如果testBean确定不为null,则可以省略this?.
        }

例:

  var webView: WebView = WebView(this)
        var settings: WebSettings = webView.settings
        var resultWith = with(settings) {
            settings.javaScriptEnabled = true
            settings.savePassword = false
            settings.builtInZoomControls = true//可以直接调用settings的方法,并省略this
            555
        }
        Log.i("LHD", "with resultWith = $resultWith")

输出结果:
with
可见with函数的返回值为函数的最后一行或者return指定的表达式

有些函数之间并没有什么明显的区别,比如also和apply,run和let等。

附上一张函数使用建议图:

kotlin

以上就是简单的总结啦。

猜你喜欢

转载自blog.csdn.net/baidu_31093133/article/details/81392845