kotlin入门学习之let、with、apply、run区别与简单使用:
let()
let()的定义是默认方法中it参数就是调用的对象本身,该方法的返回值是最后一行或者是return内容。
示例 :
var str = Student().let {
it.id = 1001
it.name = "张三"
"你好,世界"
1002
}
Log.i("initView","输出内容:$str")
// 运行结果
//I/initView: 输出内容:1002
apply
对象调用他自己的apply函数,在这个函数范围内可以任意调用公有的方法跟属性,这个函数返回的是这个对象本身
示例 :
var obj = Student().apply {
this.id = 1005
this.name = "李四"
"Hello word"
}
Log.i("initView","输出内容:$obj")
// 运行结果
/**
输出内容:Student{
id:1005
name:李四
}
*/
with
with()是一个单独的函数,传入一个对象,在函数范围中可以调用该对象的公有属性和方法有点类是apply,但是他返回值是最后一行或者是return的内容有点类是let函数
示例 :
var strs = with(Student()){
this.id = 1006
this.name = "王五"
this.getSchoolName()
"Hello word"
}
Log.i("initView","输出内容:$strs")
// 运行结果
// 输出内容:Hello word
run
run的使用类似apply,但是函数的返回值是 最后一行或者是return的内容有点类是let函数
示例 :
var students = Student().run {
this.id = 1007
this.name = "麻六"
"Hello Word"
}
Log.i("initView","输出内容:$students")
// 运行结果
// 输出内容:Hello word
最后总结:
函数名 | 参数 | 返回值 |
---|---|---|
let | it | 返回函数最后一行或者是return的内容 |
apply | 无参数 | 返回对象本身 |
with | 无参数 | 返回函数最后一行或者是return的内容 |
run | 无参数 | 返回函数最后一行或者是return的内容 |