Kotlin:使用地图变换时{}和()之间的区别? [英] Kotlin: Difference between {} and () while using map transform?
问题描述
我是Kotlin的新手. Ive始终使用带有花括号的map转换.然后-
I'm new to kotlin. Ive always used the map transform with curly braces. Then -
为什么这样做->
val x = someList.map(::SomeConstructor)
这不是吗?
val x = someList.map{ ::SomeConstructor }
在在线教程的任何地方,我都没有发现带有圆括号的地图的用法.
I didn't find usage of map with circular brackets anywhere on the online tutorials.
请尝试详细解释,或提供合适的参考文章.
Please try to explain in detail, or provide suitable reference article.
推荐答案
如果并且仅当函数的最后一个参数是lambda时,您可以将其从调用括号中提取出来,以使其内联在函数的右侧.它允许使用更好的DSL语法.
If and only if the last argument of a function is a lambda, you can extract it from the call paranthesis, to put it inline on the right of the function. It allows a nicer DSL syntax.
编辑:让我们举个例子:
一个很好的用例是上下文编程.假设您有一个可关闭的物体.您想划定它的用法,以确保不再需要它时可以正确关闭它.在Java中,您可以获得try-with-resources:
One of the good use-case is context programming. Imagine you've got a closeable object. You want to delimit its usage to ensure it's properly closed once not needed anymore. In Java, you've got the try-with-resources:
try (final AutoCloseable myResource = aquireStuff()) {
// use your resource here.
}
科特琳提供use
功能.现在,您可以执行以下任一操作:
Kotlin provide the use
function. Now, you can do either :
acquireStuff().use( { doStuff1(it) ; doStuff2(it) } )
或写:
acquireStuff().use {
doStuff1(it)
doStuff2(it)
}
它看起来像Java try-w-resource,但是可以扩展到您的任何API.允许您设计向最终用户提供高级构造的库.
It looks like a Java try-w-resource, but is extensible to any of your API. Allowing you to design libraries giving advanced constructs to end-users.
这篇关于Kotlin:使用地图变换时{}和()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!