简体   繁体   English

Kotlin 惯用的方法来检查条件并在失败时执行某些操作

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

converting java to kotlin,将 java 转换为 kotlin,

java code代码

    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());
    }

the kotlin:科特林:

    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());
    }

There are multiple functions (ie doAction_1() , doAction_2() ...) doing the same check using hasEndpoint() .有多个函数(即doAction_1()doAction_2() ...)使用hasEndpoint()进行相同的检查。

What is Kotlin idiomatic way to do something like this?什么是 Kotlin 惯用的方式来做这样的事情?

You can use a concept similar to Python decorators:您可以使用类似于 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());
}

You can use a property instead of a function for hasEndpoint or rather hasNoEndpoint and use when in place of if else您可以为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