【发布时间】:2016-01-06 08:37:35
【问题描述】:
我创建了以下函数:
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
}
我在文档中找不到上述类型的正确语法。
【问题讨论】:
-
要清楚,“命名参数”是指显式分配
contentURL参数?因为有了onCompletion = ...,你就已经在使用命名参数了。 -
是的,这就是我的意思。这是一个非常简单(但措辞不佳,将尝试解决)的问题。
-
那里很有趣。你不允许,编译器说“函数类型不允许命名参数”。我已经给 kotlin 人留言,让我们看看我们是否能得到答案,说明为什么这是不可能的。
-
啊,这很有趣。如果我放弃 onCompletion = 我可以将函数参数称为“contentURL”而不是“it”吗?
-
我认为你混淆了两件事:
onCompletion(在storeImage乐趣中)的声明可以命名为参数"for documentation"。在onCompletion的定义 中,您仍然需要使用闭包语法:onCompletion = { contentURL -> /* do stuff */ }。在调用站点上,你不能命名参数:onCompletion(URL(...)).