I'm wondering if it's preferred to call a function...
# announcements
m
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
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
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
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
yeah i like the lambda for the above reason