美文网首页程序员Android技术知识Android开发
Kotlin之“with”函数和“apply”函数

Kotlin之“with”函数和“apply”函数

作者: Troll4it | 来源:发表于2018-08-26 15:58 被阅读19次
Fighting.jpg

“with”函数

要想了解"with"函数先来看一段代码

  fun alphabet(): String {
        var stringBuilder = StringBuilder()

        for (letter in 'A'..'Z') {
            stringBuilder.append(letter)
        }
        stringBuilder.append("\n Now I know the alphabet!")
        return stringBuilder.toString()
    }

    fun alphabetWith(): String {
        var stringBuilder = StringBuilder()
        return with(stringBuilder) {
            for (letter in 'A'..'Z') {
                this.append(letter)  //this代表stringBuilder
            }
            this.append("\n Now I know the alphabet")
            this.toString()
        }
    }

运行结果

08-26 15:20:58.516 24082-24082/com.troll4it.kotlindemo I/System.out: alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ
08-26 15:20:58.517 24082-24082/com.troll4it.kotlindemo I/System.out:  Now I know the alphabet!
    alphabetWith:ABCDEFGHIJKLMNOPQRSTUVWXYZ
08-26 15:20:58.518 24082-24082/com.troll4it.kotlindemo I/System.out:  Now I konw the alphabet

通过上面代码可以看出,运行结果一样,但是alphabet()是最常规的写法, alphabetWith()方法则运用了今天的重点讲解的函数with()函数

wtih结构看起来像一种特殊的语法结构,但它是一个接收两个参数的函数:参数分别是stringBuffer和一个lambda</br>
with函数把它的第一个参数转换成第二个参数传给它的lambda的接收者,可以显示地通过this引用来访问这个接收者,但是上述方法alphabetWith()方法的this是可以省略的。</br>
with返回的值是lambda代码的返回值结果

"apply"函数

同时想了解apply函数先看一段代码

  fun alphabetApply():String=StringBuffer().apply {
        for (letter in 'A'..'Z') {
         append(letter)
        }
       append("\n Now I know the alphabet")
    }.toString()

执行结果:


08-26 15:50:48.888 25155-25155/com.troll4it.kotlindemo I/System.out: alphabetApply:ABCDEFGHIJKLMNOPQRSTUVWXYZ
08-26 15:50:48.889 25155-25155/com.troll4it.kotlindemo I/System.out:  Now I konw the alphabet

apply被声明成一个扩展函数,它的接受者变成作为实参的lambda的接受者。执行apply的结果就是StringBuffer

总结:

  • with返回的值是执行lambda代码的结果,该结果是lambda中的最后一个表达式的值。
  • apply返回的值是lambda接受者的对象

后记

摘自《Kotlin实战》

相关文章

网友评论

    本文标题:Kotlin之“with”函数和“apply”函数

    本文链接:https://www.haomeiwen.com/subject/nquoiftx.html