How to implement finalize() in kotlin?

glee8e picture glee8e · May 4, 2017 · Viewed 12.4k times · Source

Today I'm implementing a Closeable in kotlin, and as I have done in java in the past, I want to implement a finalize() as a last resort fallback in case the client code forgets to close it, rendering critical resource un-reclaimed. I consider this resource critical enough to add this fallback, despite the unreliability of this fallback. However, kotlin.Any does not declare a finalize method, which means I can't simplydo this:

class Resource: Closeable {
    fun close() {}
    override fun finalize() { close()}
}

This isn't good, at least not as good as it should be. Now I revert to plain Java as a workaround. Does anyone knows how to do this in pure Kotlin?

PS: My current workaround:

FinalizedCloseable.java:

public abstract class FinalizedCloseable implement Closeable {
    @Override protected void finalize() { close(); }
}

Kotlin:

class Resource: FinalizedCloseable(), Closeable {
    fun close() {}
    override fun finalize() { close()}
}

But this workaround requires a superclass. If next time my other Resource already got a superclass, this workaround won't work without a lot of boilerplate.


EDIT: Now I know how to implement finalize(), but IDEA kotlin plugin isn't smart enough to know that this is a finalizer and thus mark it with some warning. After struggling for a while I found how to suppress these warnings, and I want to share it:

class C {
    @Suppress("ProtectedInFinal", "Unused") protected fun finalize() {}
}

Answer

zsmb13 picture zsmb13 · May 4, 2017

The official documentation covers this.

To override finalize(), all you need to do is simply declare it, without using the override keyword:

class C {
    protected fun finalize() {
        // finalization logic
    }
}