I created the following function:
public fun storeImage(image: BufferedImage, toPath: String,
onCompletion: (contentURL: URL) -> Unit)
{
val file = File(this.storageDirectory, toPath)
log.debug("storing image: ${file.absolutePath}")
val extension = toPath.extensionOrNull()
if (!file.exists())
{
file.parentFile.mkdirs()
file.createNewFile()
}
ImageIO.write(image, extension!!, FileOutputStream(file.absolutePath))
onCompletion(URL(contentBaseUrl, toPath))
}
I can see that I can call it like this:
contentManager.storeImage(image, "1234/Foobar.jpg", onCompletion = {
println("$it")
})
Or I can use trailing closure syntax:
contentManager.storeImage(image, "1234/Foobar.jpg") {
println("$it")
}
But how do I call the store image method and call the onCompletion function using named parameters?
Edit/Example:
I would like to call the storeImage
method using a syntax similar to:
contentManager.storeImage(image, "1234/Foobar.jpg",
onCompletion = (bar: URL) : Unit -> {
//do something with bar
}
I could not find the correct syntax in the docs for the above kind of thing.
Only one parameter can be marked as vararg . If a vararg parameter is not the last one in the list, values for the subsequent parameters can be passed using named argument syntax, or, if the parameter has a function type, by passing a lambda outside the parentheses.
You can use the regular syntax for giving names to lambda parameters. This works regardless of whether you're using a named argument to pass the lambda to the function.
contentManager.storeImage(image, "1234/Foobar.jpg",
onCompletion = { bar ->
//do something with bar
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With