kotlin内联函数——takeIf和takeUnless

1.takeIf

当对一个对象调用takeIf时,如果对象满足给定的判断条件,则返回该对象;否则,返回null。因此,takeIf是对单个对象进行过滤的函数。例如,

Kotlin 复制代码
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;否则,返回该对象。例如,

Kotlin 复制代码
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。例如,

Kotlin 复制代码
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

相关推荐
阿pin9 小时前
Android随笔-kotlin withContext
android·kotlin·withcontext
树码小子10 小时前
开启 IDEA 中的断言功能
android·java·intellij-idea
Kslient10 小时前
HeaderBehavior
android
Android-Flutter11 小时前
android 动画详解
android·kotlin
小孔龙16 小时前
GraphicBuffer 跨进程共享
android
行业研究员16 小时前
Android内置GPS与腾讯地图定位技术对比分析
android·android定位·腾讯地图定位
Android-Flutter17 小时前
android WMS 详解(二)
android·kotlin
游戏开发爱好者818 小时前
App Store 上传 IPA 自动化,.p8 密钥认证与 CI/CD 接入实战
android·运维·ci/cd·小程序·uni-app·自动化·iphone
游戏开发爱好者819 小时前
iOS 推送怎么配置,APNs 推送证书、设备库与群发
android·ios·小程序·https·uni-app·iphone·webview
阿pin19 小时前
Android随笔-kotlin 高阶函数
android·kotlin·高阶函数