6

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.

Sigmund
  • 748
  • 1
  • 8
  • 28
  • Do not call `super.finalize()`. It is not required by Java contract and it is redundant in practice, since `Object.finalize()` is an empty method. – Marko Topolnik May 17 '18 at 14:21
  • Since `finalize()` is defined on class `Object` in the JVM, there has to be more to the story. I notice that you have no `override` keyword. Please correct it and try again. – Bob Dalgleish May 17 '18 at 14:22
  • @BobDalgleish Your advice contradicts the [official documentation](https://kotlinlang.org/docs/reference/java-interop.html#finalize). – Marko Topolnik May 18 '18 at 06:04

1 Answers1

8

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

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436