Override class parameter type

Hi guys,
I’m new Kotlin and need your help / advice

I have json api where response will always be

{
“code”: 0 // Always integer
“error”: {
“message”: null, // Either null or string,
“context”: // Empty list
},
“result”: null, // Can be anything, null, string, list
}

and I created two generic classes for this

open class ResponseError(
val message: String?,
val context: List<*>
)

open class Response(
val code: Int,
val error: ResponseError,
var result: Any?
)

now what I want is to override Response for login api call, where “result” will be string

class TokenResponse(
code: Int,
error: ResponseError,
result: String?
): Response(code, error, result)

but when I access result it’s still showing “Any?” in android studio, shouldn’t it be String? (because I made it more strict with String type)

Type mismatch.
Required: String?
Found: Any?

Can’t I change class parameters type hints?

No you haven’t. Your classes aren’t generic. They don’t have a type parameter. If you want to make Response generic you have to do something like

open class Response<T>(
    val code: Int,
    val error: ResponseError,
    var result: T?
)

T is a type parameter in this case. Inside your class you can use it like any other type(with some small exceptions)
Now whenever you use Response you have to specify which type to use for T.

val foo = Response<String>(0, error, "test")

or if you want to create your token response class

class TokenResponse(
    code: Int,
    error: ResponseError, 
    result: String?
): Response<String>(code, error, result)

Also most times you don’t need to write the type between the angle brackets when using a generic type, because kotlin is smart enough to figure it out from context.
You should take a look at https://kotlinlang.org/docs/reference/generics.html

I see now, thanks so much!.