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 dat
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.
finalize
Finalise is not safe, this describes some of problems with them, such as:
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.
This link shows how to override finalize, but it is a bad idea unless absolutely necessary.