Kotlin: Difference between {} and () while using map transform?

Viewed 708

I'm new to kotlin. Ive always used the map transform with curly braces. Then -

Why does this work ->

val x = someList.map(::SomeConstructor)

and this doesn't?

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.

1 Answers

What you ask is explained in this official documentation.

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.

EDIT: Let's make an example :

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

Kotlin provide the use function. Now, you can do either :

acquireStuff().use( { doStuff1(it) ; doStuff2(it) } )

or write :

acquireStuff().use {
  doStuff1(it)
  doStuff2(it)
}

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.

Related