Reputation: 13
From 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
How do you add the onError code and handle the exception?
I have the following code:
val dest = File(filePath)
source.copyRecursively(dest, true)
I do not know how to add the onError() to handle the exception
Upvotes: 1
Views: 692
Reputation: 37670
You can either pass a lambda expression with the code, or a reference to an existing function.
Here is one way to pass a 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
}
Note that in Kotlin, if a function-type parameter is last, you can pass it outside of the parentheses like this. If you want to show more explicitly that this is an error handler, you can do it by naming the argument, putting back into parentheses:
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
},
)
Upvotes: 1