Today I implement Closeable in kotlin, and, as I already did in java in the past, I want to implement finalize() as the last backup tool in case the client code forgets to close it, the critical resource is not recovered. I consider this resource critical enough to add this reserve, despite the unreliability of this reserve. However, kotlin.Any does not declare a finalize method, which means that I cannot just do this:
class Resource: Closeable { fun close() {} override fun finalize() { close()} }
This is not good, at least not as good as it should be. Now I will return to simple Java as a workaround. Does anyone know 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 the next time my other Resource already received a superclass, this workaround will not work without a lot of templates.
EDIT: now I know how to implement finalize (), but the IDEA kotlin plugin is not 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 want to share it:
class C { @Suppress("ProtectedInFinal", "Unused") protected fun finalize() {} }
java kotlin finalize
glee8e
source share