How do I declare a class containing a generic type field 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:

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

      

but Kotlin gives error: one type argument expected for APIResponse class 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 do I convert code to Kotlin?

+3


source to share


1 answer


What you have in Java is a raw type. The star-projections section of the Kotlin documentation says:

Note: Star projections are very similar to Java types, but safe.

They describe their use case:



Sometimes you want to say you don't know anything about a type argument, but you still want to use it in a safe way. The safe way here is to define a generic type projection such that every particular creation of that generic type will be a subtype of that projection.

So your class APIError

will look like this:

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

      

+7


source







All Articles