How to declare a class that contains a field with generic type in Kotlin?

In Kotlin I have a data class.

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

I want to declare another class to include this:

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

but Kotlin is giving error: One type argument expected for class APIResponse defined in com.mypackagename

In Java I can do this:

class APIError extends Exception {

    APIResponse response;

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

How can I convert the code to Kotlin?

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

for info see: https://kotlinlang.org/docs/reference/generics.html#star-projections

ps. When you know the Java-code and want the Kotlin-code, use your editor for it. in Windows -IntelliJ the shortcut is ctrl+shift+k

1 Like