apply和with的不同
① apply接收一個實例作為接收者,同時要求一個實例作為參數傳遞。
② apply返回接收者,with返回其塊內最后一個表達式的結果。
通常情況下,當你需要對一個對象某些事情并返回時,可以使用apply。而當你需要在一個對象上執行一些操作并返回一些可以使用的其他對象時,你可以使用with。
apply示例代碼:
fun getUser():User{
return User().apply{
name="andorid coder"
age=25
}
}
with示例代碼:
fun getPersonFromUser(user:User):Person{
return with(user){
Person(name,user)
}
}