https://kotlinlang.org logo
#announcements
Title
# announcements
m

Marcin Wisniowski

12/11/2017, 6:06 AM
I'm wondering if it's preferred to call a function when using
map
or pass a method reference:
Copy code
listOf("1", "2", "3").map { it.toInt() }
listOf("1", "2", "3").map(String::toInt)
Is either of these considered better? (Or am I overthinking this?)
c

Czar

12/11/2017, 7:10 AM
After compiler is done with it, these are essentially the same thing, I personally prefer method references, I think when you only do one operation, MR carries the intent more gracefully. I'm not aware of official guidelines on this though, if they at all exist.
I've thought about it a bit and sometimes I'd still use
{ it.toInt() }
when it actually improves readability. My MR argument mostly applies to
apply
,
also
,
run
, etc.
map { it.toSomething() }
reads well.
myObject.run(SomeService::doSomethingWithObject)
is better IMO than
myObject.run { SomeService.doSomethingWithObject(it) }
To sum it up, check what is more readable and use that, there is no real difference.
m

Marcin Wisniowski

12/12/2017, 1:21 AM
Makes sense, thanks for the insight! Both "map it to Int" and "map String to Int" are very readable sentences, but I guess I will stick with the MR in this case as the String type is more visible.
p

pablisco

12/15/2017, 9:19 AM
The only argument fo using the lambda is that it reads like:
map it to Int
so a bit more like natural language. so it depends on the case.
c

cygnus

12/17/2017, 9:35 PM
yeah i like the lambda for the above reason