destructor in Kotlin programming language

前端 未结 1 383
孤城傲影
孤城傲影 2021-01-17 10:18

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

相关标签:
1条回答
  • 2021-01-17 11:01

    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.

    0 讨论(0)
提交回复
热议问题