Do Kotlin-native have destructors?
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 to share