Search code examples
kotlinreturn-valueextension-methods

Kotlin function return with any one return type from two different data type without specifying Any as a return type?


I want to allow any one of these two return type (ApiResponse || ErrorResponse). But Return Type should not be a object or Any.

fun getAllUser() : Any? {
    val flag = true
    return if(flag){
        ApiResponse(true)
    } else {
        ErrorResponse(500)
    }
}

With return type (Any), Not able to write an extension function to do specific action with with two different return type. I want t specify Two responses.

In My case, I want to write different Extension function for ApiResponse &  ErrorResponse class. 

Is it possible to return either ErrorResponse or ApiResponse in a same function?

Solution

  • Create a sealed interface that both of your classes implement:

    sealed interface Response<out T>
    data class ApiResponse<T>(val data: T): Response<T>
    data class ErrorResponse(val errorCode: Int): Response<Nothing>
    
    fun getAllUser() : Response<Boolean> {
        val flag = true
        return if(flag){
            ApiResponse(true)
        } else {
            ErrorResponse(500)
        }
    }
    

    Then you can write extension functions that handle either type:

    fun Response<Boolean>.foo() {
        when (this) {
            is ApiResponse<Boolean> -> { TODO() }
            is ErrorResponse -> { TODO() }
        }
    }
    

    Inside the branches of this when statement, the input will be smart cast to the appropriate type.