我想用多个重载选项覆盖基类的方法,这样就可以从该基类的方法调用它,但只有标记有覆盖的与原始签名匹配的选项才会更改。
open class EgBase {
fun lookAt(thing: Any) {
reactTo(thing)
}
open fun reactTo(thing: Any) {
println("Standard reaction")
}
}
class EgWorkingInheritor: EgBase() {
override fun reactTo(thing: Any) {
println("Custom reaction")
}
}
class EgFailingInheritor: EgBase() {
fun reactTo(thing: Int) {
println("Reaction for ints only!")
}
}
fun main() {
EgBase().lookAt(0.1) // Standard reaction
EgWorkingInheritor().lookAt("a") // Custom reaction
EgFailingInheritor().lookAt(7) // Standard reaction
EgBase().reactTo(0.1) // Standard reaction
EgWorkingInheritor().reactTo("b") // Custom reaction
EgFailingInheritor().reactTo(2) // Reaction for ints only!
}
在所提供的示例中,第二组调用工作得很好-重载的方法被识别,但在第一组调用中,当从非overriden方法调用时,EgFailingInheritor的reactTo重载没有被识别。我该怎么解决这个问题?
编辑:我知道在这个例子中,只重载lookAt方法要好得多,但在我实际做的事情中,reactTo调用有一些行为,我不想重复重写。
如果以抽象的方式使用这些类,则仅用于Int
s的reactTo
函数也将失败,这通常是类层次结构的使用方式:
val eg: EgBase = EgFailingInheritor()
eg.reactTo(2) // Standard reaction
您需要实际覆盖想要以不同方式表现的函数,并从那里手动委派。这将解决两个问题:
class EgFailingInheritor: EgBase() {
override fun reactTo(thing: Any) {
when (thing) {
is Int -> reactTo(thing) // smart cast Int thing, calls overload
else -> super.reactTo(thing)
}
}
fun reactTo(thing: Int) {
println("Reaction for ints only!")
}
}