Kotlin为闭包/lambda命名了参数语法



我创建了以下函数:

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))
}

我可以这样称呼它:

contentManager.storeImage(image, "1234/Foobar.jpg", onCompletion = {
    println("$it")
})

或者我可以使用尾随闭包语法:

contentManager.storeImage(image, "1234/Foobar.jpg") {
    println("$it")
}

但是,如何使用命名参数调用store image方法和onCompletion函数呢?

编辑/示例:

我想使用类似于的语法来调用storeImage方法

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

我在文档中找不到上述内容的正确语法。

您可以使用常规语法为lambda参数命名。无论您是否使用命名参数将lambda传递给函数,这都能起作用。

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

最新更新