Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin super.finalize()

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.

like image 732
Igor Skryl Avatar asked May 17 '18 14:05

Igor Skryl


1 Answers

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().

like image 60
Marko Topolnik Avatar answered Nov 13 '22 04:11

Marko Topolnik