【Android】kotlin的let run apply also等等学习记录

好久没有更新啦,今天学习了一些kotlin的语法

class MainActivity : AppCompatActivity() {

    private val testArray: ArrayList by lazy { ArrayList() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.i("hello", "let = " + testLet().toString())
        Log.i("hello", "apply = " + testApply().toString())
        Log.i("hello", "with = " + testWith())
        Log.i("hello", "run = " + testRun())

        testRun2()
        testAlso()
        testRepeat()

        Log.i("hello", "takeIf = " + testTakeIf())
        Log.i("hello", "takeUnless = " + testTakeUnless())

        6.takeIf { it < 7 }?.let {
            compareValues(1, 2)
            Log.i("hello", "2 method = $it")
        }
    }

    private fun testLet(): ArrayList {
        //T.let 将T作为it,let的返回值为函数体内最后一条语句的返回值
        testArray.let {
            it.add("let1")
            it.add("let2")
            Log.i("hello", it.toString())
            return it
        }
    }

    private fun testApply(): ArrayList {
        //T.apply T将函数体中的每一条语句按顺序执行,返回T
        return testArray.apply {
            add("apply3")
            add("apply4")
            add("apply5")
            remove("let1")
            Log.i("hello", "apply this=" + this)
        }
    }

    private fun testWith(): Boolean {
        //with(T) 将函数体中的每一条语句按顺序执行,返回值为函数体内最后一条语句的返回值
        return with(testArray) {
            add("with6")
            add("with7")
            remove("apply8")
        }
    }

    private fun testRun(): Int {
        //T.run T将函数体中的每一条语句按顺序执行,返回最后一条语句的返回值
        return testArray.run {
            add("run9")
            add("run10")
            Log.i("hello", "run this=" + this)
            remove("let1")
            compareValues(3, 4)
        }
    }

    private fun testRun2() {
        //kotlin中的run函数,返回最后一句语句的返回
        var i = 1
        val date = kotlin.run {
            i++
            Date()
            //compareValues(2,3)
        }
        Log.i("hello", "run2 = $date")
    }

    private fun testAlso() {
        //T.also T作为it,返回T
        val also = Date().also {
            Log.i("hello", "also this = $it")
            testArray.add("also11")
        }
        Log.i("hello", "also = $also")
    }

    private fun testRepeat() {
        //其中it为次数,如此处i分别为 0,1,2 repeat 返回Unit
        repeat(3) {
            Log.i("hello", "repeat = $it")
        }
    }

    private fun testTakeIf(): Int? {
        //T.takeIf 当T满足if条件时返回T,否则返回null
        return 6.takeIf {
            it < 5
        }
    }

    private fun testTakeUnless(): Int? {
        //T.takeIf 当T不满足条件时返回T,满足条件返回null
        return 6.takeUnless {
            it < 5
        }
    }
}

另外有一篇文章写的还挺清楚的,可以参考一下Kotlin之let,apply,run,with等函数区别2

自己动手实现一下,感觉理解了一些,一起加油鸭~

你可能感兴趣的:(Android开发)