Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin type mismatch while passing in parameter

I'm overriding a function in a parent class that takes a parameter of type Any?. I want Any? to be an instance of type Venue, so that I can pull out it's id, however, I can't override the function using getModelId(model: Venue?) because that's not how it's defined in the super class. What's the best way to make sure that for this use case the class instance of model is Venue? and I can pull out the data inside of it that I want?

open class VenueAdapter: ParentClass() {
    override fun getModelId(model: Any?): Any? {
        //here I want to be able to pull the id out of the Venue class instance
        return model.id

}

abstract class ParentClass {
    //I've also tried defining it with a type parameter fun <M : Any?> getModelId(model: M) but that hasnt' worked.
    abstract fun getModelId(model: Any?) : Any? 
}


data class Venue (id: String)

I've also considered

override fun getModelId(model: Any?): Any? {
    when (model) {
        is Venue -> return model.id
    }

}

but I'm not sure that's the best way

like image 676
Rafa Avatar asked Feb 01 '26 08:02

Rafa


2 Answers

If it's okay to return null in case the passed model is not an instance of Venue, then you can just use a safe cast and a safe call as simple as:

override fun getModelId(model: Any?): Any? = (model as? Venue)?.id

Otherwise, either add your default value after the Elvis operator ?:, like this:

override fun getModelId(model: Any?): Any? = (model as? Venue)?.id ?: defaultId

Or fall back to an if or when statement that will involve a smart cast:

override fun getModelId(model: Any?): Any? = 
    if (model is Venue)
        model.id else
        defaultId

override fun getModelId(model: Any?): Any? = 
    when (model) {
        is Venue -> model.id
        else -> defaultId
    }
like image 121
hotkey Avatar answered Feb 04 '26 00:02

hotkey


You can make the ParentClass generic:

interface ParentClass<in T, out R> {
    fun getModelId(model: T?): R
}

open class VenueAdapter : ParentClass<Venue, Int?> {
    override fun getModelId(model: Venue?): Int? {
        return model?.id
    }
}
like image 36
s1m0nw1 Avatar answered Feb 04 '26 00:02

s1m0nw1