什么是标准函数?
是指在Standard.kt文件中定义的函数,在任何的Kotlin代码都可以自由地调用。
1.let函数
这个在?.后面加let函数就可以不用每次都坐非空判断了
study?.let {
it.readBooks()
it.doHomework()
}
2.with函数,返回值是with函数的最后一行toString的返回值
fun doWith(){
val list= listOf("Apple","pear","Banana","Orange")
val result= with(StringBuilder()){
append("Start eating fruits.\n")
for (fruit in list){
append(fruit).append("\n")
}
append("Ate all fruits")
toString()
}
println(result)
}
3.run函数,返回值也是函数最后一行的toString()的返回值
fun doRun(){
val list= listOf("Apple","pear","Banana","Orange")
val result=StringBuilder().run {
append("Start eating fruits.\n")
for (fruit in list){
append(fruit).append("\n")
}
append("Ate all fruits")
toString()
}
println(result)
}
4.apply函数,返回值是StringBuilder()对象
fun doApply(){
val list= listOf("Apple","pear","Banana","Orange")
val result = StringBuilder().apply {
append("Start eating fruits.\n")
for (fruit in list){
append(fruit).append("\n")
}
append("Ate all fruit")
toString()
}
println(result.javaClass)
}
网友评论