Scala 中的映射函数 [英] map function in Scala

查看:31
本文介绍了Scala 中的映射函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 上的 * def,第二种方式中我们正在调用数字上的 * def.

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 中的映射函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆