Does kotlin-native have destructors?

血红的双手。 提交于 2019-12-10 12:56:19

问题


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?


回答1:


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") 
   }
}


来源:https://stackoverflow.com/questions/44747862/does-kotlin-native-have-destructors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!