lolo
lolo

Reputation: 5

Why do i need to specify constructor argument as nullable generic type?

I'm trying to make OK() to call ApiResponse constructor. When I give null to ApiResponse constructor argument, it shows error that type mismatches.

If I change data type to T? it works. Why is it happening? Default upper bound of T is Any? so i thought it won't be any problem to assign null.

class ApiResponse<T> private constructor(
        val data: T, // If I change data type to T?, no error
        val message: String?
) {
    companion object {
        fun <T> OK(): ApiResponse<T> {
            return ApiResponse(null, null)
        }

        fun <T> OK(data: T): ApiResponse<T> {
            return ApiResponse(data, null)
        }
    }
}

I've searched with keywords kotlin, generic, constructor, nullable, T but i could not find answer.

Upvotes: 0

Views: 48

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198033

In

fun <T> OK(): ApiResponse<T> {
   return ApiResponse(null, null)
}

if someone calls ApiResponse.OK<String>(), then it tries to construct an ApiResponse where data is null and also of type String, which is incompatible. None of your types prevent that call -- when you have a generic type argument to the function like that, the caller can specify any T they please, including a nonnull type.

You must either return an ApiResponse<T?>, or not have an argumentless OK factory method.

Upvotes: 2

Related Questions