0
点赞
收藏
分享

微信扫一扫

【Kotlin】Kotlin笔记12-标准函数(run,with,apply)


Kotlin笔记12-标准函数和静态方法-run,with,apply


7. 标准函数和静态方法

  • 标准函数with,run,apply
  1. with

with: 参数一:任意类型的对象,参数二:Lambda表达式

序号

Tips

1

Lambda表达式的最后一行作为返回值返回

​标准格式:​

val result = with(obj) {
//这里是obj的上下文
"value" //with函数的返回值
}

​Example:​

fun eatFruit() {
val list = listOf("Apple", "Banana", "Orange", "Pear")
val builder = StringBuilder()
builder.append("Start eating Fruits! ")
for ((index, fruit) in list.withIndex()) {
builder.append(fruit).let {
if (index != list.size - 1) it.append(" ")
}
}
builder.append(". Ate all fruits.")
val result = builder.toString()
println(result)
}

​采用with:​

//with优化
fun eatFruit1(){
val list= listOf("Apple","Banana","Orange","Pear")
val result= with(StringBuilder()){
append("Start eating fruits. ")
for (fruit in list){
append(fruit).append(" ")
}
append("Ate all fruits.")
toString()
}
println(result)
}
  1. run

run: 接受一个Lambda参数

1

Tips

1

run函数不能直接调用,调用某个对象的run函数

​标准格式:​

val result = obj.run {
// 这里是obj的上下文
"value" // run函数的返回值
}

​采用run:​

fun eatFruit2(){
val list= listOf("Apple","Banana","Orange","Pear")
val result= StringBuilder().run {
append("Start earting fruits. ")
for (fruit in list){
append(fruit).append(" ")
}
append("Ate all fruits.")
toString()
}
println(result)
}
  1. apply

apply: 接受一个Lambda参数

序号

Tips

1

在某个对象上调用,在表达式中提供调用对象的上下文

2

apply无法指定返回值,直接返回调用对象本身

​标准格式:​

val result = obj.apply {
// 这里是obj的上下文
}
// result == obj

​采用apply:​

fun eatFruit3(){
val list= listOf("Apple","Banana","Orange","Pear")
val result=StringBuilder().apply {
append("Start eating fruits. ")
for (fruit in list){
append(fruit).append(" ")
}
append("Ate all fruits.")
}
println(result)
}

实用场景 - Intent
​​​Example:​

val intent = Intent(context,SecondActivitu::class.java)
intent.putExtra("param1", "data1")
intent.putExtra("param2", "data2")
context.startActivity(intent)

​apply优化:​

val intent(context,SecondActivity::class.java).apply {
putExtra("param1","data1")
putExtra("param2","data2")
}
context.startActivity(intent)


举报

相关推荐

0 条评论