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
A destructuring declaration creates multiple variables at once. You have declared two new variables: name and age , and can use them independently: println(name) println(age) A destructuring declaration is compiled down to the following code: val name = person.
In Java, we can destroy the Singleton Object by below method. so the constructor will be called the next time. In the same way how to destroy the Kotlin Singleton object. object CacheManager{ init { //some operations } fun destroy(){ //How to destroy? } }
In Kotlin, there are two constructors: Primary constructor - concise way to initialize a class. Secondary constructor - allows you to put additional initialization logic.
Kotlin is 100% interoperable with the Java programming language and major emphasis has been placed on making sure that your existing codebase can interact properly with Kotlin. You can easily call Kotlin code from Java and Java code from Kotlin. This makes adoption much easier and lower-risk.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With