Kotlin中apply和let的区别

Posted zhangjin1120

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Kotlin中apply和let的区别相关的知识,希望对你有一定的参考价值。

目录

apply的用法

class Student 
    var name: String? = null
    var age: Int? = null


fun main() 
    var s = Student().apply 
        name = "zhangjin"
        age = 20
    
    println(s.name + " " + s.age)

输出结果如下:

let的用法

class Student 
    var name: String? = null
    var age: Int? = null



fun main() 
    var s = Student().let 
        it.name = "zhangjin"
        it.age = 20
    
    println(s)

    var s2 = Student().let 
        it.name = "zhangjin"
        it.age = 20
        it.age
    
    println(s2)

    var s3 = Student().let 
        it.name = "zhangjin"
        it.age = 20
        it
    
    println(s3.name)

看下运行效果:

对于Unit不理解的,可以看这篇:Kotlin中的Unit。从运行结果,可以看出let把闭包中最后一行代码的返回值,赋值给var变量。

以上是关于Kotlin中apply和let的区别的主要内容,如果未能解决你的问题,请参考以下文章

Kotlin中let,with,apply,run,also的区别

Kotlin中let,with,apply,run,also的区别

Kotlin 内联函数let,with,run,apply,also区别和用法

Kotlin笔记:with/let/run/apply/also区别

Kotlin笔记:with/let/run/apply/also区别

Kotlin笔记:with/let/run/apply/also区别