【问题标题】:Using generic as parameter in constructor Kotlin在构造函数 Kotlin 中使用泛型作为参数
【发布时间】:2019-11-11 04:43:17
【问题描述】:

我正在使用两个具有不同输入类型的构造函数,一个是字符串,另一个是泛型​​。问题是在使用 Kotlin 时,它只使用字符串构造函数并忽略了泛型

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
    }
}

用法

    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"))
                }

【问题讨论】:

  • 是否有理由同时保留isSuccesserrorMessage?我只保留错误消息并将isSuccess 更改为函数或val 在错误为空的情况下返回true。也许引入静态工厂来调用错误/成功构造函数,我认为当你有 2 个构造函数本质上改变你的对象所代表的内容时,这有点令人困惑。如果TString,这也将解决构造函数“冲突”的问题。

标签: android generics kotlin kotlin-android-extensions constructor-overloading


【解决方案1】:

你可以在 kotlin 中给出命名参数。也就是说,如果存在两个以上同名的构造函数或函数,我们可以将参数显式指定为名为一个。这里我建议明确提及参数data

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

【讨论】:

    【解决方案2】:

    目前你的DataResponse 类代表两个不同的东西。一个是错误消息,另一个是成功时的实际数据。 isSuccess 也是多余的,因为当 data 为非空时它始终为 true,如果 errorMessage 为非空,它始终为 false

    我会通过以下方式更改设计:

    sealed class DataResponse
    
    class SuccessResponse<T>(val data: T?)
    
    class ErrorResponse(val errorMessage: String)
    

    现在你有两个独立的类,它们都有相同的超类型DataResponse。这样,您将始终知道自己在处理什么。

    用法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      相关资源
      最近更新 更多