destructor in Kotlin programming language

夙愿已清 提交于 2019-12-01 14:19:39

问题


I am new to Kotlin, have written a class in kotlin to perform database operation

I have defined database connection in constructor using init but I want to close database connection using destructor.

Any Idea of how to achieve this using kotlin destructor?

Currently I have wrote a separate function to close connection, which i want to have it using destructor like any other programming language like php,etc


回答1:


Handling resources that need to be closed in Kotlin

You can make your Database Wrapper extend Closeable. You can then use it like this.

val result = MyResource().use { resource ->
    resource.doThing();
}

This way inside the use block your resource will be available, afterwards you will get back result, which is what doThing() returns, and your resource will be closed. As you haven't stored it in a variable you also avoid accidentally using the resource after it is closed.

Why to avoid finalize

Finalise is not safe, this describes some of problems with them, such as:

  • They are not guaranteed to run at all
  • When they do run there can be delays before it runs

The link sums up the problems like this:

Finalizers are unpredictable, often dangerous, and generally unnecessary. Their use can cause erratic behavior, poor performance, and portability problems. Finalizers have a few valid uses, which we’ll cover later in this item, but as a rule of thumb, you should avoid finalizers.

C++ programmers are cautioned not to think of finalizers as Java’s analog of C++ destructors. In C++, destructors are the normal way to reclaim the resources associated with an object, a necessary counterpart to constructors. In Java, the garbage collector reclaims the storage associated with an object when it becomes unreachable, requiring no special effort on the part of the programmer. C++ destructors are also used to reclaim other nonmemory resources. In Java, the try-finally block is generally used for this purpose.

If you really need to use finalize

This link shows how to override finalize, but it is a bad idea unless absolutely necessary.



来源:https://stackoverflow.com/questions/48623441/destructor-in-kotlin-programming-language

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