gpt4 book ai didi

kotlin - Kotlin 编程语言中的析构函数

转载 作者:IT老高 更新时间:2023-10-28 13:39:57 50 4
gpt4 key购买 nike

我是 Kotlin 新手,在 kotlin 中写了一个类来执行数据库操作

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

知道如何使用 kotlin 析构函数来实现这一点吗?

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

最佳答案

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

您可以使您的数据库包装器扩展 Closeable .然后你可以像这样使用它。

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

这样在 use block 中你的资源将可用,之后你会得到结果,这是 doThing() 返回的结果,你的资源将被关闭。由于您没有将其存储在变量中,因此您也可以避免在关闭后意外使用资源。

为什么要避免finalize

Finalise 不安全,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.

如果你真的需要使用finalize

This link展示了如何覆盖 finalize,但除非绝对必要,否则这是一个坏主意。

关于kotlin - Kotlin 编程语言中的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48623441/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com