在Kotlin我有一个数据类.
data class APIResponse<out T>(val status: String, val code: Int, val message: String, val data: T?)
Run Code Online (Sandbox Code Playgroud)
我想声明另一个类来包含这个:
class APIError(message: String, response: APIResponse) : Exception(message) {}
Run Code Online (Sandbox Code Playgroud)
但是Kotlin给出错误:com.mypackagename中定义的类APIResponse需要一个类型参数
在Java中我可以这样做:
class APIError extends Exception {
APIResponse response;
public APIError(String message, APIResponse response) {
super(message);
this.response = response;
}
}
Run Code Online (Sandbox Code Playgroud)
如何将代码转换为Kotlin?
Java中的内容是原始类型.在关于星形投影的部分中,Kotlin文档说:
注意:星形投影非常类似于Java的原始类型,但是很安全.
他们描述了他们的用例:
有时您想说您对类型参数一无所知,但仍希望以安全的方式使用它.这里安全的方法是定义泛型类型的这种投影,该泛型类型的每个具体实例都将是该投影的子类型.
APIError因此,您的班级成为:
class APIError(message: String, val response: APIResponse<*>) : Exception(message) {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
514 次 |
| 最近记录: |