在 Scala 编程中,使用匿名函数是很常见的事情.当我决定通过两种不同方式创建一个匿名函数输出的矢量时 方法一: var hold1=(1 to 5).map(_*2) 方法二: var hold2=(1 to 5).map(2*) 我想知道这两个声明之间有什么区别?
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 ?
推荐答案简而言之-它们是完全相同的. 第一种方法:
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))第二种方法:
var hold2 = (1 to 5).map(2*)再次重写:
var hold2 = (1 to 5).map(number => 2.*(number))所有发生的事情都以第一种方式调用数字2上的*定义,然后以第二种方式调用数字上的*定义.
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.
更多推荐
Scala中的map函数
发布评论