Kotlin 编程语言中的析构函数
destructor in Kotlin programming language
我是Kotlin新手,在kotlin中写了一个class来进行数据库操作
我已经使用 init 在构造函数中定义了数据库连接,但我想使用析构函数关闭数据库连接。
知道如何使用 kotlin 析构函数实现这一点吗?
目前我已经编写了一个单独的函数来关闭连接,我希望它像任何其他编程语言一样使用析构函数,如 php,等等
在 Kotlin 中处理需要关闭的资源
您可以让您的数据库包装器扩展 Closeable
。然后你可以像这样使用它。
val result = MyResource().use { resource ->
resource.doThing();
}
这样在 use 块中您的资源将可用,之后您将得到结果,这就是 doThing()
returns,并且您的资源将被关闭。由于您没有将它存储在变量中,因此您也可以避免在资源关闭后意外使用该资源。
为什么要避免finalize
Finalise 不安全,this 描述了它们的一些问题,例如:
- 根本无法保证运行
- 当他们这样做时 运行 之前可能会有延迟 运行s
link 总结问题是这样的:
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
展示了如何覆盖最终确定,但除非绝对必要,否则这是一个坏主意。
我是Kotlin新手,在kotlin中写了一个class来进行数据库操作
我已经使用 init 在构造函数中定义了数据库连接,但我想使用析构函数关闭数据库连接。
知道如何使用 kotlin 析构函数实现这一点吗?
目前我已经编写了一个单独的函数来关闭连接,我希望它像任何其他编程语言一样使用析构函数,如 php,等等
在 Kotlin 中处理需要关闭的资源
您可以让您的数据库包装器扩展 Closeable
。然后你可以像这样使用它。
val result = MyResource().use { resource ->
resource.doThing();
}
这样在 use 块中您的资源将可用,之后您将得到结果,这就是 doThing()
returns,并且您的资源将被关闭。由于您没有将它存储在变量中,因此您也可以避免在资源关闭后意外使用该资源。
为什么要避免finalize
Finalise 不安全,this 描述了它们的一些问题,例如:
- 根本无法保证运行
- 当他们这样做时 运行 之前可能会有延迟 运行s
link 总结问题是这样的:
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.