In Scala programming use an anonymous function is a usual thing . when i decide to creat a vector as out put of an anonymous function from two different ways
way one :
var hold1=(1 to 5).map(_*2)
way two:
var hold2=(1 to 5).map(2*)
I want to know what is the difference between those two declaration ?
Asked
Active
Viewed 623 times
1

Ravindu De Silva
- 29
- 5
2 Answers
4
In short - they are exactly the same. First approach:
var hold1 = (1 to 5).map(_*2)
Let's rewrite this another way to demonstrate what's really happening under the hood (no syntactic sugar)
var hold1 = (1 to 5).map(number => number.*(2))
Second approach:
var hold2 = (1 to 5).map(2*)
Rewrite again:
var hold2 = (1 to 5).map(number => 2.*(number))
All that is happening is in first way are invoking the *
def on the number 2 and in the second way we are invoking the *
def on the number.

Tanjin
- 2,442
- 1
- 13
- 20
-
1it might be interesting to look at the generated code, however. `_ * 2` almost certainly creates an anonymous lambda, but `2 *` might not. – Rob Starling Apr 09 '17 at 02:47
-
They are only exactly the same if you assume that `Int.*` is symmetric! That is not true in the general case. – Jörg W Mittag Apr 09 '17 at 10:14
-
Why does the second version which calls the `.*` method not require the `_`? Should it not be `(1 to 5).map(2 * _)` ? – Jon Taylor Apr 09 '17 at 11:59
0
Both are exactly same. You can use underscore character in many different ways. Refer this link for more details.