Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin named parameter syntax for closure/lambda

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.

like image 606
Jasper Blues Avatar asked Jan 06 '16 08:01

Jasper Blues


People also ask

When a lambda function has only one parameter what is its default name in Kotlin?

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.


1 Answers

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
    })
like image 70
yole Avatar answered Oct 04 '22 16:10

yole