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
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
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With