美文网首页
kotlin中的takeIf和takeUnless函数

kotlin中的takeIf和takeUnless函数

作者: Bfmall | 来源:发表于2022-11-03 21:52 被阅读0次

takeIf和takeUnless函数的学习笔记###

/**
 * DESC   :
 */

class KtBaseInternalFunTest02 {

    companion object {
        const val TAG = "KtBaseInternalFunTest02"
    }

    fun testTaskIf01() {
        val result = checkSystem("hahha", "666666")
        Log.d(TAG, "testTaskIf01==>result="+result)//testTaskIf01==>result=null

        val result2 = checkSystem2("hahha", "666666")
        Log.d(TAG, "testTaskIf01==>result2="+result2)//testTaskIf01==>result2=你的权限不够,无法访问

        val result3 = checkSystem2("admin", "123456")
        Log.d(TAG, "testTaskIf01==>result3="+result3)//testTaskIf01==>result3=admin
    }

    /**
     * TODO
     * takeIf : 接收一个判断条件表达式,如果判断表达式为 true 则返回对象本身,false返回 null。
     */
    private fun checkSystem(username: String ,password: String): String? {
        /**
         * username.takeIf
         * checkLogin如果为true,返回username本身
         * checkLogin如果为false,返回null
         */
        return username.takeIf { checkLogin(username, password) }
    }

    /**
     * takeIf + 空合并 ?:
     * 当在 takeIf之后链式调用其他函数,不要忘记执行空检查或安全调用(?.),因为他们的返回值是可为空的。
     */
    private fun checkSystem2(username: String ,password: String): String? {
        /**
         * username.takeIf
         * checkLogin如果为true,返回username本身
         * checkLogin如果为false,返回null
         */
        return username.takeIf { checkLogin(username, password) } ?: "你的权限不够,无法访问"
    }


    private fun checkLogin(username:String, password: String) : Boolean{
        return if ("admin".equals(username) && "123456".equals(password)) true else false
    }


    private var takeInfo : String? = /*"我幼稚"*/null

    fun getTakeInfo() = takeInfo

    fun setTakeInfo(takeInfo : String) {
        this.takeInfo = takeInfo
    }

    /**
     * TODO
     * takeUnless和takeIf功能相反
     * takeIf : 接收一个判断条件表达式,如果判断表达式为 true 则返回对象本身,false返回 null。
     * takeUnless: 与 takeIf 相反, 如果判断表达式为 true 则返回 null,false 返回对象本身。
     */
    fun testTakeUnless01() {
        val result = getTakeInfo()?.takeUnless {
            it.isNullOrBlank()//如果返回true,则result=null
        }
        Log.d(TAG, "testTakeUnless01==>result="+result)//testTakeUnless01==>result=null

        val result2 = getTakeInfo()?.takeUnless {
            it.isNullOrBlank()
        } ?: "未初始化值"
        Log.d(TAG, "testTakeUnless01==>result2="+result2)//testTakeUnless01==>result2=未初始化值
    }
}

相关文章

网友评论

      本文标题:kotlin中的takeIf和takeUnless函数

      本文链接:https://www.haomeiwen.com/subject/cegazrtx.html