美文网首页
kotlin的“static inheritable funct

kotlin的“static inheritable funct

作者: zbiext | 来源:发表于2018-06-22 10:28 被阅读0次

昨天,写BaseApplication时候,一些“静态方法、属性”都放在companion object(ps:kotlin 根本没有静态这个概念,而伴生对象本身是一个单例对象,kotlin的字节码中可以看到)中,MyApplication继承BaseApplication了

//基类
open class BaseApplication : MultiDexApplication() {
    init {
        initInstance()
    }

    private fun initInstance() {
        instance = this
    }

    override fun onCreate() {
        super.onCreate()
        //instance = this

        mainThreadHandler = Handler(Looper.getMainLooper())
        mainThreadId = Process.myTid()
    }

    companion object {
        lateinit var instance: BaseApplication

        private var mainThreadHandler: Handler? = null
        private var mainThreadId: Int? = 0

        /** 上下文(Application) */
        fun getContext(): Context {
            return instance.applicationContext
        }

        /** 主线程Handler */
        fun getMainHandler(): Handler {
            return mainThreadHandler!!
        }

        /** 主线程Id */
        fun getMainThreadId(): Int {
            return mainThreadId!!
        }
    }
}
//子类
class MyApplication: BaseApplication()

如果你想子类调用BaseApplication中的“静态方法”,如:

MyApplication.getContext() // wrong

发现只能用父类名.getContext(),说明 kotlin 的“静态” 不能被子类继承,顺便翻墙查了一下,然后,改造代码:

//基类
open class BaseApplication : MultiDexApplication() {
    init {
        initInstance()
    }

    private fun initInstance() {
        instance = this
    }

    override fun onCreate() {
        super.onCreate()
        //instance = this

        mainThreadHandler = Handler(Looper.getMainLooper())
        mainThreadId = Process.myTid()
    }

    companion object {
        lateinit var instance: BaseApplication

        private var mainThreadHandler: Handler? = null
        private var mainThreadId: Int? = 0

        /** 上下文(Application) */
        fun getContext(): Context {
            return instance.applicationContext
        }

        /** 主线程Handler */
        fun getMainHandler(): Handler {
            return mainThreadHandler!!
        }

        /** 主线程Id */
        fun getMainThreadId(): Int {
            return mainThreadId!!
        }
    }

    open class BaseApplicationCompanion {
        open fun getContext() : Context = BaseApplication.getContext()
        open fun getMainHandler() : Handler = BaseApplication.getMainHandler()
        open fun getMainThreadId() : Int = BaseApplication.getMainThreadId()
    }
}
//子类
class MyApplication: BaseApplication() {

    companion object : BaseApplicationCompanion()
}

ps:kotlin的伴生对象是可以继承于另一个类
另外,一个(非单独)伴生对象不能继承另外一个(非单独)伴生对象,如图:


companion object

最后,贴出kotlin的字节码(说明伴生对象就是一个静态内部类)


伴生对象.jpg

相关文章

网友评论

      本文标题:kotlin的“static inheritable funct

      本文链接:https://www.haomeiwen.com/subject/brnhyftx.html