Using generic as parameter in constructor Kotlin

Viewed 628

I m using two constructor with different input types one as string and other as generic. The problem is while using Kotlin its only using the string constructor and ignores the generic

class DataResponse<T> {
    var isSuccess: Boolean = false
        private set
    var errorMessage: String? = null
    var data: T? = null

    constructor(success: Boolean, data: T) {
        this.isSuccess = success
        this.data = data
    }

    constructor(success: Boolean, errorMessage: String) {
        this.isSuccess = success
        this.errorMessage = errorMessage
    }
}

usage

    if (apiResponse.code() == 200) {
                    Observable.just(DataResponse<List<ResultDTO>>(true,
 apiResponse.body()?.resultList)) ---> **(error on this line forcing to convert it to string)**
                } else {
                    Observable.just(DataResponse(false, "Something went wrong"))
                }
2 Answers

You can give named parameters in kotlin. That is if more than two constructors or functions with same name exists, we can explicitly specify the parameter as named one. Here I suggest to explicity mention the parameter data.

    if (apiResponse.code() == 200) {
        Observable.just(DataResponse<List<ResultDTO>>(true,data=
        apiResponse.body()?.resultList))
    } else {
        Observable.just(DataResponse(false, "Something went wrong"))
    }

Currently your DataResponse class represents two different things. One is an error message and the other one is actual data in case of success. isSuccess is redundant too because it is always true when data is non-null and always false if errorMessage is non-null.

I would change the design in the following way:

sealed class DataResponse

class SuccessResponse<T>(val data: T?)

class ErrorResponse(val errorMessage: String)

Now you have two separate classes, both having the same supertype DataResponse. This way you will always know what you are dealing with.

Usage:

when(dataResponse) {
    is SuccessResponse -> TODO("deal with data")
    is ErrorResponse -> TODO("deal with error")
}
Related