kotlin 标准库中提供了一些函数,用来在临时的作用域内执行代码。在这些作用域内,无需通过对象名就能访问对象。
作用域函数有:run、with、T.run、T.let、T.also、T.apply
一、run
单独使用时没啥作用
run{
println("my name is wmj")
}
但是它有返回值,返回值是最后一个对象
// str = "my name is wmj"
val str = run {
val name = "wmj"
"my name is $name"
}
二、with
with 括号中传入对象,用this操作对象,this可以省略
val person = Person("wmj", 25)
with(person) {
name = ""
age = 30
}
如果对象是可空的,this 不可以省略
val person2: Person? = Person("wmj2", 26)
with(person2) {
this?.name = ""
this?.age = 30
}
三、T.run
T.run 用this操作对象,this可以省略,和 with 作用一样。
person.run {
name = ""
age = 30
}
但是如果对象是可空的,用 T.run 比 with 更方便
person?.run {
name = ""
age = 30
}
四、T.let
T.let 用it操作对象
person.let {
it.name = "wmj"
it.age = 30
}
如果对象是可空的
person2?.let {
it.name = "wmj"
it.age = 30
}
T.run 比 T.let 在使用上更加简洁,但是 T.let 有以下优势
- 更清楚的区分变量与外部类的成员
-
this不能省略的情况下,it比this更短更清晰 -
it可以更换成其他名字
person?.let { student ->
student.name = "wmj"
student.age = 22
}
五、 T.also
T.also 用 it 操作对象,和 T.let作用一样
person.also {
it.name = "wmj"
it.age = 30
}
但是他们的返回值不同,T.let 返回最后一个对象的值,T.also 返回 this
val a: Int? = person?.let {
it.name = ""
it.age
}
val b: Person? = person?.also {
it.name = ""
it.age = 30
}
六、T.apply
T.apply 把 this 作为参数,并返回了 this,很方便链式调用
val starter = Intent(context, AActivity::class.java)
.apply { putExtra("key", 1) }
.apply { putExtra("key2", 2) }







网友评论