【发布时间】:2018-04-15 07:56:17
【问题描述】:
我正在重写父类中的一个函数,该函数采用 Any? 类型的参数。我想要任何?成为 Venue 类型的实例,以便我可以提取它的 id,但是,我不能使用 getModelId(model: Venue?) 覆盖该函数,因为它不是在超类中定义的。确保对于这个用例,模型的类实例是 Venue? 并且我可以从中提取我想要的数据的最佳方法是什么?
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)
我也考虑过
override fun getModelId(model: Any?): Any? {
when (model) {
is Venue -> return model.id
}
}
但我不确定这是最好的方法
【问题讨论】:
-
这违反了里氏替换原则。
ParentClass的用户可以传递任何东西,并且实现应该能够处理它。你的VenueAdapter保证比它覆盖的要少(或者如果你想这样看它需要更多),这意味着当你插入这个实现时,曾经突然工作的调用者不会。您可能需要重新检查设计,看看是否有更好的设置。
标签: android oop inheritance kotlin