12

In kotlin native there is memScoped function that automatically free allocated memory when control is going out of scope. Is there something like destructors for local objects?

Vladimir Berezkin
  • 3,580
  • 4
  • 27
  • 33

1 Answers1

17

Current Kotlin/Native does not provide mechanism for calling a method when certain object is no longer needed in memory (finalizer in Java speech) but inline lambdas easily allow to implement mechanisms, similar to RAII in C++. For example, if you want to be sure, that some resource is always released after leaving certain scope, you may do:

class Resource {
  fun take() = println("took")
  fun free() = println("freed")
}

inline fun withResource(resource: Resource, body: () -> Unit) =
 try {
   resource.take()
   body()
 } finally {
   resource.free()
 }

fun main(args: Array<String>) {
   withResource(Resource()) { 
       println("body") 
   }
}
Suresh
  • 1,925
  • 1
  • 18
  • 21
Nikolay Igotti
  • 580
  • 2
  • 7
  • 1
    Is there a plan to add destructors at all? Or would you rather not because this kind of deterministic behavior is not possible to achieve anyway with Kotlin's other targets? – Vitaly Apr 19 '18 at 19:55
  • There are no current plan to add general purpose destructors. However, somewhat similar functionality could be achieved with weak references, present in Kotlin/Native. – Nikolay Igotti Aug 16 '18 at 07:59