2017-07-28 149 views
3

在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) {} 

但错误科特林所赐:预计类APIResponse一类的说法在com.mypackagename

在Java中,我可以定义请执行以下操作:

class APIError extends Exception { 

    APIResponse response; 

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

如何将代码转换为Kotlin?

回答

7

你在Java中有什么是原始类型。在上star-projections的部分,在科特林文件说:

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) {} 
+0

感谢。我还没有尝试过,但我认为这应该工作。 – Arst