在我的android应用中:
suspend fun getTraidersList(): TransportResponse = withContext(Dispatchers.IO) {
// some common methods
try {
val response: Response<List<Trader>> = traderMonitorRestClient.getTraidersList()
// some common methods
} catch (e: Throwable) {
// some comon methods
}
}
suspend fun executeTraderOperation(traderOperation: Trader.Operation, base: String, quote: String): TransportResponse = withContext(Dispatchers.IO) {
// some common methods
try {
val response: Response<Void> = traderMonitorRestClient.executeTraderOperation(traderOperation.toString().toLowerCase(), base.trim(), quote.trim(), sender, key)
// some common methods
} catch (e: Throwable) {
// some comon methods
}
}
如您所见,我有2种方法,其中有许多常用方法。我想在单独的方法中提取此常用方法。 我想将函数作为参数传递给my_common_method。 可以在Kotlin中这样做吗?
suspend fun my_common_method(fun some_custom_function) {
// some common methods
try {
val response: Response<*> = some_custom_function()
// some common methods
} catch (e: Throwable) {
// some comon methods
}
}
也许有更好的解决方案?
在getTraidersList()
中,功能some_custom_function
是getTraidersList()
。在executeTraderOperation
中,函数some_custom_function
是executeTraderOperation
。
在科特林有可能吗?
答案 0 :(得分:2)
您可以做的是使用高阶函数:
suspend fun my_common_method(block: suspend () -> Response<TransportResponse>) {
// some common methods
try {
val response = block()
// some common methods
} catch (e: Throwable) {
// some comon methods
}
}
然后您只需致电my_common_method {getTraidersList() }