Kotlin super.finalize()

守給你的承諾、 提交于 2021-02-08 15:16:07

问题


While migration to Kotlin from Java I faced with a problem. I overrided Object's finalize() method:

@Override
protected void finalize() throws Throwable {
    stopTimer();
    super.finalize();
}

When I tried to do the same with Kotlin I found to solutions. The first one is from the doc:

 protected fun finalize() {
    stopTimer()
    super.finalize()
}

And the second one from the article (it's in Russian):

@Suppress("ProtectedInFinal", "Unused")
protected fun finalize() {
    stopTimer()
    super.finalize()
}

But in both cases I can't call super.finalize() according to IDE, as it says unresolved reference:finalize

Maybe anybody knows how to get this work in Kotlin? Thanks.


回答1:


Here's the contract of finalize in Java:

The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.

Therefore you are not required to call through to the superclass. You would be calling through to an empty implementation.

The need to call super.finalize() arises only in classes not directly deriving from kotlin.Any.

The rest of the story is already told in the official documentation: just declare a protected fun finalize().



来源:https://stackoverflow.com/questions/50393502/kotlin-super-finalize

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!