https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
m

martmists

10/10/2023, 1:56 PM
I'm looking through documentation and previous posts, but how would I get a cross-platform destructor working? I know for JVM I can use
finalize()
, but I can't find anything for native. I'm aware native does provide Cleaner, but that requires the object to already be deallocated, meaning it's impossible to pass the object to some finalize method. Ideally I could structure my code like this:
Copy code
class C {
    protected fun finalize() { ... }
    
    private val cleaner = createCleaner(this) { this.finalize() }
}
but as the docs state, createCleaner(this) leaks a reference to C and it will never be deallocated. What could I do here? Unfortunately putting a CleanerWrapper around every single class/instance is not feasible.
c

Casey Brooks

10/10/2023, 2:03 PM
finalize()
is well-known to be a poor mechanism for cleaning up resources, and it’s better to use a more explicit mechanism in your own application logic. I’d recommend something like AutoCloseable (added in 1.8.20) and managing the lifecycle of those resources yourself with
.use { }
e

ephemient

10/10/2023, 2:16 PM
also both JVM and Kotlin/Native have a
Cleaner
concept for adding an action to after an object is collected, https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ref/Cleaner.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.native.ref/create-cleaner.html but you need to be careful not to introduce reference cycles
Java
finalize()
is deprecated in most versions of Java and actually removed in the most recent: https://openjdk.org/jeps/421
as that summary states, you should either use the "try-with-resources" pattern (e.g.
AutoCloseable
+
.use {}
in Kotlin, as Casey mentioned) or cleaners
m

martmists

10/10/2023, 3:15 PM
So the best option would be to manually keep track of reference counts and call custom destructors when I deem necessary? (basically implementing a pseudo-GC) for context, I'm working on a custom interpreted language with specific deconstructor logic out of my control