【问题标题】:kotlin, how to make a internal function also able to be override in a sub class (in other module)kotlin,如何使内部函数也能够在子类中被覆盖(在其他模块中)
【发布时间】:2021-09-28 04:32:54
【问题描述】:

android 项目有多个模块。模块 A 在 kotlin 中有一些基类

package xxx.module_a

open class InModule_A {
   protected function action() {...}
}

class Runner() {

    fun doSomething() {
        InModule_A().action(). // it is NOT compile, but if the action() is internal it is ok since they are in same module
    }

}

模块A中的Runner类需要访问InModule_A()类成员函数action()

并且InModule_A.action() 应该只在module A 内可见,并且在其他模块的派生类中被覆盖。

module B 中,它具有派生自InModule_A 的类InModule_B

package xxx.module_b

class InModule_B {

   protected override function action() {// if InModule_A().action() were a internal it would not be able to override here 
   
   super.action()
   ... ...
   }
}

如何使函数具有内部可见性并能够在派生类中覆盖?

【问题讨论】:

    标签: kotlin derived-class


    【解决方案1】:

    我不是 100% 确定我理解,但也许创建一个调用受保护函数的替代函数会适合您的情况。

    open class InModule_A {
        protected open fun action() {}
        internal fun internalAction() = action()
    }
    
    class Runner() {
    
        fun doSomething() {
            InModule_A().internalAction()
        }
    
    }
    

    【讨论】:

    • 谢谢!除非进行更大的重构,否则这似乎是唯一的选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 2020-08-26
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    相关资源
    最近更新 更多