加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何在Kotlin中声明包含泛型类型字段的类?

发布时间:2020-12-15 04:39:52 所属栏目:Java 来源:网络整理
导读:在Kotlin我有一个数据类. data class APIResponseout T(val status: String,val code: Int,val message: String,val data: T?) 我想声明另一个类来包含这个: class APIError(message: String,response: APIResponse) : Exception(message) {} 但是Kotlin给
在Kotlin我有一个数据类.

data class APIResponse<out T>(val status: String,val code: Int,val message: String,val data: T?)

我想声明另一个类来包含这个:

class APIError(message: String,response: APIResponse) : Exception(message) {}

但是Kotlin给出错误:com.mypackagename中定义的类APIResponse需要一个类型参数

在Java中我可以这样做:

class APIError extends Exception {

    APIResponse response;

    public APIError(String message,APIResponse response) {
        super(message);
        this.response = response;
    }
}

如何将代码转换为Kotlin?

解决方法

Java中的内容是原始类型.在 star-projections节中,Kotlin文档说:

Note: star-projections are very much like Java’s raw types,but safe.

他们描述了他们的用例:

Sometimes you want to say that you know nothing about the type argument,but still want to use it in a safe way. The safe way here is to define such a projection of the generic type,that every concrete instantiation of that generic type would be a subtype of that projection.

因此,您的APIError类变为:

class APIError(message: String,val response: APIResponse<*>) : Exception(message) {}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读