Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional (Result / Error) translation using Kotlin runCatching

Tags:

kotlin

I am trying to use Kotlin runCatching feature along with response + error translation functions. Something like

class SomeClassThatCallsServiceX {

    fun remoteCall(input): TransformedResult {
        kotlin.runCatching{ serviceX.call(input)}
            .onSuccess { return functionToTranslateServiceXResponse(it)}
            .onFailure{ throw functionToranslateServiceXError(it)}
    }
}

functionToTranslateServiceXResponse : (OriginalResult) -> TransformedResult
functionToranslateServiceXError : (Throwable) -> RuntimeException
  

However Kotlin is giving me the following error - A 'return' expression required in a function with a block body ('{...}'). If you got this error after the compiler update, then it's most likely due to a fix of a bug introduced in 1.3.0 (see KT-28061 for details)

Running with Kotlin 1.4.

I am still new to Kotlin- wondering if I am doing something fundamentally wrong here. Any help would be greatly appreciated.


Update: tried the following pattern, basic test cases seem to be working fine. Would love to know what others think of the pattern

class SomeClassThatCallsServiceX {

    fun remoteCall(input): TransformedResult {
        return kotlin.runCatching{ serviceX.call(input)}
            .mapCatching(functionToTranslateServiceXResponse)
            .onFailure(functionToranslateServiceXError)
            .getOrThrow()
    }
}

functionToTranslateServiceXResponse : (OriginalResult) -> TransformedResult
functionToranslateServiceXError : (Throwable) -> Unit
  
like image 299
u07103 Avatar asked Jan 19 '26 16:01

u07103


1 Answers

I think there are couple of issues here:

class SomeClassThatCallsServiceX {

    // You are not returning `TransformedResult` but Result<TransformedResult> 
    // but Result cannot be returned by kotlin https://stackoverflow.com/q/52631827/906265
    fun remoteCall(input) {
        // error mentioned that "return" was missing but you cannot return Result
        kotlin.runCatching{ serviceX.call(input)}
            .onSuccess { return functionToTranslateServiceXResponse(it) }
            .onFailure{ throw functionToranslateServiceXError(it) }
    }
}

Having a callback could be a solution (pseudocode):

fun remoteCall(input Any, callback: Callback) {
    kotlin.runCatching{ serviceX.call(input)}
            .onSuccess { callback.success(it) }
            .onFailure { callback.error(it) }
}

Have a tiny example on Kotlin Playground website based on the above https://pl.kotl.in/W8wMDEzN1

like image 140
Ivar Avatar answered Jan 22 '26 15:01

Ivar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!