Kotlin编程语言中的析构函数 [英] destructor in Kotlin programming language

查看:693
本文介绍了Kotlin编程语言中的析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Kotlin的新手,已经在Kotlin中编写了一个用于执行数据库操作的类

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

我已经使用init在构造函数中定义了数据库连接,但是我想使用析构函数来关闭数据库连接.

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

关于如何使用Kotlin析构函数实现此目标的任何想法?

Any Idea of how to achieve this using kotlin destructor?

目前,我已经编写了一个单独的函数来关闭连接,我想像其他任何编程语言(如php等)一样使用析构函数来实现它

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

推荐答案

处理需要在Kotlin中关闭的资源

您可以使您的数据库包装程序扩展 Closeable .然后,您可以像这样使用它.

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();
}

这样,在use块内,您的资源将可用,然后您将返回结果,这是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.

最终确定是不安全的,描述了一些与他们有关的问题,例如:

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 ++程序员不要将终结器视为Java的C ++析构函数的类似物.在C ++中,析构函数是回收与对象关联的资源的常规方法,而对象是构造函数的必要对等物.在Java中,垃圾回收器在对象无法访问时回收与该对象关联的存储,而程序员则无需进行任何特殊的工作. C ++析构函数还用于回收其他非内存资源.在Java中,通常将try-finally块用于此目的.

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.

如果您真的需要使用finalize

此链接显示了如何覆盖finalize,但这是一个坏主意,除非绝对必要.

If you really need to use finalize

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

这篇关于Kotlin编程语言中的析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆