Home > Software engineering >  Kotlin function return with any one return type from two different data type without specifying Any
Kotlin function return with any one return type from two different data type without specifying Any

Time:04-03

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?

CodePudding user response:

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.

CodePudding user response:

I got a Idea to return either ErrorResponse or ApiResponse in a same function.

By using [Λrrow][1] library I'm able to achieve this like the following function.

fun getAllUser() : Either<ErrorResponse,ApiResponse>? {
    val flag = true
    ResponseEntity(ErrorResponse(500),HttpStatus.INTERNAL_SERVER_ERROR)
    ResponseEntity.internalServerError().build<ErrorResponse>()
    val response: Either<ErrorResponse,ApiResponse> = return if(flag){
        Either.right(ApiResponse(true))
    } else {
        Either.left(ErrorResponse(500))
    }
    return response
}

CodePudding user response:

I suggest using Result class. Either the one provided by Kotlin or, even better, your own implementation. Here is one of the examples of using custom implementation, along with the explanation. This should give you all the information you need.

  • Related