簡體   English   中英

Kotlin 慣用的方法來檢查條件並在失敗時執行某些操作

[英]Kotlin idiomatic way to check a condtion and do something if fail

將 java 轉換為 kotlin,

代碼

    private boolean hasEndpoint() {
        if (mSettings == null || mSettings.getEndpoint() == null) {
            if (isDebugMode()) {
                throw new IllegalArgumentException("endpoint is not set !!!");
            }
            return false;
        }
        return true;
    }

   public void doAction_1(...) {
        if (!hasEndpoint()) {
            callback.onError(ENDPOINT_UNINITIALIZED, "ERROR_END_POINT_NOT_SET");
            return;
        }
        //do the action with valid endpoint
        doSomething_1(mSettings.getEndpoint());
    }

科特林:

    private fun hasEndpoint(): Boolean {
        if (mSettings?.endpoint == null) {
            require(!isDebugMode) { "endpoint is not set !!!" }
            return false
        }
        return true
    }

    fun doAction_1() {
        if (!hasEndpoint()) {
            callback.onError(ENDPOINT_UNINITIALIZED, "ERROR_END_POINT_NOT_SET")
            return
        }
        //do the action with valid endpoint
        doSomething_1(mSettings!!.getEndpoint());
    }

有多個函數(即doAction_1()doAction_2() ...)使用hasEndpoint()進行相同的檢查。

什么是 Kotlin 慣用的方式來做這樣的事情?

您可以使用類似於 Python 裝飾器的概念:

// Add your check here
fun withCheck(action: () -> Unit) {
    if (!hasEndpoint()) {
        callback.onError(ENDPOINT_UNINITIALIZED, "ERROR_END_POINT_NOT_SET")
        return
    }
    action()
}

// Add your actions enclosed with `withCheck`
fun action1() = withCheck {
    doSomething_1(mSettings!!.getEndpoint());
}

fun action2() = withCheck {
    doSomething_2(mSettings!!.getEndpoint());
}

您可以為hasEndpointhasNoEndpoint使用property而不是function ,並使用when代替if else

private val hasNoEndpoint: Boolean
    get() = when {
        mSettings?.endpoint != null -> false
        isDebugMode -> throw IllegalArgumentException("endpoint is not set !!!")
        else -> true
    }

// use this in withCheck function as in enzo's answer
fun withEndpoint(action: () -> Unit): Unit = when {
    hasNoEndpoint -> callback.onError(ENDPOINT_UNINITIALIZED, "ERROR_END_POINT_NOT_SET")
    else -> action()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM