kotlinasynchronousoverloadingsuspend

Function overloading between suspend and non-suspend function is not possible in Kotlin


I want to provide synchronous version of my asynchronous function, but I can't over load, the function have structure like this. Who can explain, why I can't, and is there any other way to overload function for my case.

suspend fun foo(a: Int, b: Int): Int {
    delay(100)
    return a + b
}

fun foo(a: Int, b: Int): Result<Int> {
    //delay
    return Result.success( a + b)
}

Solution

  • In the java when we want to overload the function we have to change it's signature. Which is function name or parameter. When we define suspend in kotlin we just identify of the environment of function where it can be run like coroutine. You can check this link for information: java signature

    To give example you can change like that:

    fun foo(a: Int, b: Int): Int {
        return a + b
    }
    suspend fun foo(a: Int, b: Int, isSuspend: boolean): Result<Int> {
        if(isSuspend) {
            delay(100)
            return Result.success( a + b)
        }else {
            return Result.failure("Call suspend")
        }
    }