2017-07-28 150 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