简体   繁体   English

Kotlin命名为closure / lambda的参数语法

[英]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? 但是如何调用store图像方法并使用命名参数调用onCompletion函数?

Edit/Example: 编辑/实施例:

I would like to call the storeImage method using a syntax similar to: 我想使用类似于以下语法调用storeImage方法:

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. 我无法在上述类型的文档中找到正确的语法。

You can use the regular syntax for giving names to lambda parameters. 您可以使用常规语法为lambda参数指定名称。 This works regardless of whether you're using a named argument to pass the lambda to the function. 无论您是否使用命名参数将lambda传递给函数,这都有效。

contentManager.storeImage(image, "1234/Foobar.jpg", 
    onCompletion = { bar ->
       //do something with bar
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM