With
val result = with(obj){
//这里是obj的上下文,可以进行所有关于obj的操作
"value"//返回值,with函数的返回值
}
作用:可以是的连续调用同一个对象的多个方法的时候让代码变得更加简洁
fun appendBuilder(){
val list = listOf("Apple", "Banana", "Orange", "Watermelon", "Peach", "Pear")
var builder = StringBuilder()
var result = with(builder){
append("He is eating:\n")
for (fruit in list){
append(fruit).append(" ")
}
append("\n")
append("He ate all the fruits.")
toString()
}
println(result)
}
Run
val result = obj.run{
//这里是obj的上下文
"value"//run函数的返回值
}
作用和with相同,都是提供给obj一个上下文,并返回一个值
fun runBuilder(){
val list = listOf("Apple", "Banana", "Orange", "Watermelon", "Peach", "Pear")
val builder = StringBuilder()
val result = builder.run {
append("Start eating fruit:\n")
for (fruit in list){
append(fruit)
append("\n")
}
append("Ate all fruits")
toString()
}
println(result)
}
Apply
val result = obj.apply{
//obj的上下文
}
//result == obj,自动返回调用对象本身