4个标准函数的使用(with,run,apply,let)
直接上代码
/**
* 4个标准函数的使用,with,run,apply,let,注意其中的区别哦
*/
fun main(args:Array<String>) {
val list = listOf("Apple","Banana","Orange","Pear","grape")
val bulider = StringBuilder()
val result = with(bulider){
append("Use with start eating fruits. ")
for(f in list){
append(f).append(",")
}
append("Ate all fruits.")
toString()
}
println(result)
val result1 = StringBuilder().run{
append("Use run start eating fruits. ")
for(f in list){
append(f).append(",")
}
append("Ate all fruits.")
toString()
}
println(result1)
val result2 = StringBuilder().apply{
append("Use apply start eating fruits. ")
for(f in list){
append(f).append(",")
}
append("Ate all fruits.")
//toString()
}
result2.toString()
println(result2)
var result3 = StringBuilder()
result3.let{
it.append("Use let start eating fruits. ")
for(f in list){
it.append(f).append(",")
}
it.append("Ate all fruits.")
it.toString()
}
println(result3)
//var result3 = StringBuilder()
StringBuilder().let{
it.append("Use let start eating fruits. ")
for(f in list){
it.append(f).append(",")
}
it.append("Ate all fruits.")
it.toString()
println(it)
}
}
执行结果
Use with start eating fruits. Apple,Banana,Orange,Pear,grape,Ate all fruits.
Use run start eating fruits. Apple,Banana,Orange,Pear,grape,Ate all fruits.
Use apply start eating fruits. Apple,Banana,Orange,Pear,grape,Ate all fruits.
Use let start eating fruits. Apple,Banana,Orange,Pear,grape,Ate all fruits.
Use let start eating fruits. Apple,Banana,Orange,Pear,grape,Ate all fruits.
Process finished with exit code 0