【发布时间】:2017-07-05 09:39:29
【问题描述】:
在阅读了this article about Memory Leaks 之后,我想知道在 Kotlin Android 项目中使用 lambdas 是否安全。确实,lambda 语法让我更轻松地编程,但是内存泄漏呢?
作为问题的一个例子,我从我的一个项目中获取了一段代码,我在其中构建了一个 AlertDialog。这段代码在我项目的 MainActivity 类中。
fun deleteItemOnConfirmation(id: Long) : Unit {
val item = explorerAdapter.getItemAt(id.toInt())
val stringId = if (item.isDirectory) R.string.about_to_delete_folder else R.string.about_to_delete_file
val dialog = AlertDialog.Builder(this).
setMessage(String.format(getString(stringId), item.name)).setPositiveButton(
R.string.ok, {dialog: DialogInterface, id: Int ->
val success = if (item.isDirectory) ExplorerFileManager.deleteFolderRecursively(item.name)
else ExplorerFileManager.deleteFile(item.name)
if (success) {
explorerAdapter.deleteItem(item)
explorerRecyclerView.invalidate()
}
else Toast.makeText(this@MainActivity, R.string.file_deletion_error, Toast.LENGTH_SHORT).show()
}).setNegativeButton(
R.string.cancel, {dialog: DialogInterface, id: Int ->
dialog.cancel()
})
dialog.show()
}
我的问题很简单:为正负按钮设置的两个 lambdas 会导致内存泄漏吗? (我的意思是,kotlin lambdas 是否简单地转换为 Java 匿名函数?)
编辑:也许我已经得到了答案in this Jetbrains Topic。
【问题讨论】:
-
那么当 lambdas 不使用封闭对象的任何方法或字段时,它是否会捕获封闭对象?它们是不同的点:discuss.kotlinlang.org/t/…discuss.kotlinlang.org/t/…
-
非常感谢。很快就会听他们的:)
-
其实没有这么有用的事实。无论如何谢谢你
标签: android lambda memory-leaks kotlin