2017-07-28 17 views
3

私はデータクラスを持っています。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がエラーを与えている:私はJavaではcom.mypackagename

にすることができます定義されたクラスAPIResponseのために期待される一つの型引数をこれをどうすればいいですか:

コードをKotlinに変換するにはどうすればよいですか?

答えて

7

あなたの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) {} 
+0

感謝。私はまだ試していないが、これはうまくいくと思う。 – Arst

関連する問題