Do Kotlin-native have destructors?

The kotlin native has a memScoped function that automatically frees the allocated memory when the control goes out of scope. Are there some sort of destructors for local objects?

+3


source to share


1 answer


Current Kotlin / Native does not provide a mechanism for calling a method when a particular object is no longer needed in memory (finalizer in Java speech), but built-in lambdas make it easy to implement mechanisms similar to RAII in C ++. For example, if you want to make sure that some resource is always released after leaving a certain area, you can 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") 
   }
}

      

+10


source







All Articles