如何在 Kotlin 的 copyRecursively 中使用 onError

how to use onError in copyRecursively in Kotlin

来自https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/copy-recursively.html

fun File.copyRecursively(
    target: File,
    overwrite: Boolean = false,
    onError: (File, IOException) -> OnErrorAction = { _, exception -> throw exception }
): Boolean

如何添加onError代码和处理异常?

我有以下代码:

  val dest = File(filePath)
  source.copyRecursively(dest, true)

不知道如何添加onError()来处理异常

您可以将 lambda 表达式与代码一起传递,也可以传递对现有函数的引用。

这是传递 lambda 的一种方法:

val dest = File(filePath)
source.copyRecursively(dest, overwrite = true) { file, exception ->
    // do something with file or exception
    // the last expression must be of type OnErrorAction
}

请注意,在 Kotlin 中,如果函数类型的参数在最后,您可以像这样在括号外传递它。 如果你想更明确地表明这是一个错误处理程序,你可以通过命名参数,放回括号中来实现:

val dest = File(filePath)
source.copyRecursively(
    target = dest,
    overwrite = true,
    onError = { file, exception ->
        // do something with file or exception
        // the last expression must be of type OnErrorAction
    },
)