kotlin内联函数——takeIf和takeUnless
1.takeIf
当对一个对象调用takeIf
时,如果对象满足给定的判断条件,则返回该对象;否则,返回null
。因此,takeIf
是对单个对象进行过滤的函数。例如,
class User {
var name: String? = null
var age = 99
fun set(ageParam: Int) {
age = ageParam
}
fun get(): Int {
return age
}
}
val user = User().takeIf {
it.age == 99
}
Log.d(TAG,"user对象:$user")
2.takeUnless
takeUnless
的逻辑与takeIf
相反。当对一个对象调用takeUnless
时,如果对象满足给定的判断条件,则返回null
;否则,返回该对象。例如,
class User {
var name: String? = null
var age = 99
fun set(ageParam: Int) {
age = ageParam
}
fun get(): Int {
return age
}
}
val user = User().takeUnless {
it.age == 999
}
Log.d(TAG,"user对象:$user")
注意:在takeIf和takeUnless函数调用后,如还有其他调用,请在调用时用?.判空。因为两者返回的对象可能为null。例如,
class User {
var name: String? = null
var age = 99
fun set(ageParam: Int) {
age = ageParam
}
fun get(): Int {
return age
}
}
Log.d(TAG, "User#age:${
User().takeUnless {
it.age == 999
}?.age
}"
)
推荐文章
Scope functions | Kotlin Documentation