converting java to 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()
.
What is Kotlin idiomatic way to do something like this?
You can use a concept similar to Python decorators:
// 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
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()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.