Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using generic as parameter in constructor Kotlin

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"))
                }
like image 213
Auto-Droid ツ Avatar asked Jul 31 '26 15:07

Auto-Droid ツ


1 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"))
    }
like image 120
Antonio Avatar answered Aug 02 '26 06:08

Antonio



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!