Kotlin学习

Kotlin学习7-内置函数

2022-09-02  本文已影响0人  海内灬存知己
val name = "null,a,b,c"

1:apply内置函数,返回本身,链式调用

        name.apply {
            //一般匿名函数都持有it,但是apply不持有it,而是this,this又是可以省略的,所以:
            println(this.length)
            println(length)
        }
        //真正使用apply的写法如下:链式调用,代码分段,返回的是自己本身
        name.apply {
            println(length)
        }.apply {
            println(this[length - 1])
        }.apply {
            println(toLowerCase())
        }

2:let内置函数,仅展开,无法链式调用,不返回自己,返回最后一行,匿名函数持有it

        val let = listOf(1, 2, 3, 4, 5).let {
            //it==list
            it.first() + it.first()
        }
        println(let)

3:run内置函数,匿名函数持有的是this(同apply),返回的是最后一行(同let),仔细想是很巧妙的

        val doMyThing: (Boolean) -> Boolean = { b ->
            println(b)
            b
        }
        val doMyThing2 = { b: Boolean ->
            println(b)
        }
        name.run {
            //此时的this是name,返回值是boolean
            this.isNotEmpty()
        }.run {
            //此时的this已经是boolean了,返回值是boolean
            if (this) {
                name.contains("a")
            } else {
                false
            }
            //doMyThing无需传参,因为默认是this,这种是具名函数/或者匿名函数,正好练习一下匿名函数的两种写法!
        }.run(doMyThing).run(doMyThing2)

4:with内置函数,跟run基本相同,只是写法不同

        fun getString(s: String): Any {
            TODO("Not yet implemented")
        }
        //具体函数
        with(name, ::getString)
        //隐式函数
        val a = with(name) {
            this.contains("a")
        }
        val b = with(a) {
            if (this) {
                name.contains("a")
            } else {
                false
            }
        }
        with(b, doMyThing)

5,also,谁点also,返回值就是谁,跟apply有点像,但匿名函数持有it跟let类似

        val c: String = name.also {
            true
            123
        }

6,takeif

        name.takeIf { true }//返回name
        name.takeIf { false }//返回null

7,takeUnless 正好跟takeif相反

        name.takeUnless { false }//返回name
        name.takeUnless { true }//返回nul
上一篇下一篇

猜你喜欢

热点阅读