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变量。