如何重载重写方法以便从非重写方法调用它?
How to overload an overriden method so it is called from non-overriden methods?
我想用多个重载选项覆盖基 class 的方法,以便可以从该基 class 的方法调用它,但只有标有覆盖的选项匹配原签名已更改。
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!
}
在提供的示例中,第二组调用完美运行 - 重载方法被识别,但在第一组调用中,当从非重写方法调用时,无法识别 EgFailingInheritor 的 reactTo 重载。我该如何解决这个问题?
编辑:我知道在示例中重载 lookAt 方法会好得多,但在我实际做的事情中,我不想重复重写 reactTo 调用的行为。
如果您以抽象的方式使用这些 class,您仅用于 Int
的 reactTo
功能也会失败,这通常是 class 层次结构的方式使用:
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!")
}
}
我想用多个重载选项覆盖基 class 的方法,以便可以从该基 class 的方法调用它,但只有标有覆盖的选项匹配原签名已更改。
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!
}
在提供的示例中,第二组调用完美运行 - 重载方法被识别,但在第一组调用中,当从非重写方法调用时,无法识别 EgFailingInheritor 的 reactTo 重载。我该如何解决这个问题?
编辑:我知道在示例中重载 lookAt 方法会好得多,但在我实际做的事情中,我不想重复重写 reactTo 调用的行为。
如果您以抽象的方式使用这些 class,您仅用于 Int
的 reactTo
功能也会失败,这通常是 class 层次结构的方式使用:
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!")
}
}