Scala map() vs map{}

Spark 3.5 Scala 算子性能对比:map vs mapPartitions 处理 1GB 文本数据实测 本文深入对比了Spark 3.5中Scala算子的性能差异,重点分析了map和mapPartitions在处理1GB文本数据时的表现。通过实测数据展示,mapPartitions在复杂业务逻辑下性能提升显著,但内存消耗较高,为开发者提供了优化策略和决策建议。 阅读详情

I was wondering the other day what the difference really was, in Scala, between

1 val list = List(1, 2, 3, 4)
2 list.map(x => x * x)

and

1 val list = List(1, 2, 3, 4)
2 list.map { x => x * x }

So, I figured I’d take a look at the map function defined on the List class. I winded up finding the definition in the TraversableLike trait as follows:

 1 def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
 2   def builder = { // extracted to keep method size under 35 bytes, so that it can be JIT-inlined
 3     val b = bf(repr)
 4     b.sizeHint(this)
 5     b
 6   }
 7   val b = builder
 8   for (x <- this) b += f(x)
 9   b.result
10 }

Let’s ignore the builder for now since it’s the less important part of this question. We’re interested in the first set of parameters, f: A => B. This seems to be a normal argument yet we can apply it in two different ways. That got me thinking a little bit and so I decided to play around a bit to see if I can figure this out anecdotally, before looking up the proper literature.

Non-Function Arguments

I first wanted to try with some simple functions that didn’t have functions as arguments to see if this format is generally applicable. I came up with some simple tests.

 1 def echo(x: String) = println(x)
 2  
 3 echo{"hello"}    // valid
 4 echo("hello")    // valid
 5  
 6  
 7 def echoName(name: String, x: String) = println("$name: $x")
 8  
 9 echoName{"John", "hello"}        // invalid
10 echoName("John", "hello")        // valid
11 echoName({"John"}, {"hello"})    // valid

So from this it seems to indicate that braces are not interchangeable with parenthesis. However, it does seem that "John" and {"John"} are interchangeable. In fact, if we look at the REPL we see:

1 val s1 = {"hello"}     // s1: String = hello
2 val s = "hello"        // s: String = hello

This may not be a surprise to some, but that means that something like echo {"hello"}can really just be thought of as a shorthand for echo({"hello"}). But what about {x => x * x}. We can assume that just returns a function, correct? So that would means we can assume that these are functionally equivalent:

1 val list = List(1, 2, 3, 4)
2 list.map(x => x * x)
3 list.map({x => x * x})

And, anecdotally, this seems to be true.

Back to Functions

So based on our findings, what is the point of the curly braces and when would they be useful. Let’s do some experiments with a little more meat and see if we can find an answer. First let’s try a slightly larger map example.

 1 val list = List(1, 2, 3, 4)
 2  
 3 // not valid (compile-error)
 4 list.map(x =>
 5   val y = x * x
 6   val z = y * x
 7   Math.sin(z / x)
 8 )
 9  
10 // valid
11 list.map{x =>
12   val y = x * x
13   val z = y * x
14   Math.sin(z / x)
15 }

Ah ha, so there is a good reason to use curly braces. It looks like the parenthesis version cannot handle multiple statements and is only expecting a single expression. Furthermore, I found this bit interesting as well:

1 val f1 = (x : Int => x * x)    // invalid - compiler error (can't resolve x)
2 val f2 = (x : Int) => x * x    // valid
3 val f3 = {x : Int => x * x}    // valid

The same syntax using parenthesis cannot be used to define the function outside of the map unlike the version with curly-braces. Very interesting.

The Real Story

Okay, at this point I feel like I’ve made some interesting findings, but I’m curious what the Internet has to say about such things. So I figured I’d let her weigh in. I came across a few different posts:

Surprisingly, all three answers were by the same person. For someone strapped for time when it comes to blogging, he sure does seem to make a lot of appearances on this topic. ;-D

All in all, there seems to be quite a bit of discussion with some grey areas still that I still don’t fully understand. In those cases the compiler seems to be the specification, which is never preferable (IMO) for many reasons. Oh Scala, you are an interesting little language.

【MDC开发者实战】多传感器融合算法在自动驾驶中的配置与优化 本文详细介绍了华为MDC平台在自动驾驶中多传感器融合算法的配置与优化实践。通过前融合与后融合技术,结合摄像头、激光雷达和毫米波雷达的数据,提升感知精度与可靠性。文章还分享了ARXML配置、标定技巧、算法调优及性能优化等实战经验,帮助开发者高效实现自动驾驶系统的传感器融合。 阅读详情

相关推荐

K-means在关键词聚类中的尝试

K-means在文本聚类中的尝试 K-means算法是无监督的聚类算法。它的算法思想是:先随机选取K个对象作为初始的聚类中心。然后计算每个对象与各个种子聚类中心之间的距离,把每个对象分配给距离它最近的聚类中心。聚类中心以及分配给它们的对象就代表一个聚类。一旦全部对象都被分配了,每个聚类的聚类中心会根据聚类中现有的对象被重新计算。 K-means算法的关键点在于: 初始k个聚类中心的选择 距离的计...

BigPig_LittleTail的博客 5573

scala集合之map使用

前言 map在scala的开发中算是使用非常频繁的集合之一,本文将通过实际的代码演示下map在scala中的使用 1、创建map scala中的map主要分为2种类型,可变的map和不可变的map,这个和数组类似 def main(args: Array[String]): Unit = { //不可变map val map1 = Map("name" -> "zhangsan","age" -> 12) println(map1) println(

congge_study的博客 1万+

V-rep机器人仿真(Win10):UR5+RG2+Kinect+YOLOV3+DDPG+Pytorch(第四部分:YOLOV3图像识别)

这是一个V-rep机器人仿真实验,较为简单,适合初学者在入门图像识别、机器学习、机器人学的内容时进行学习与训练。 实验涉及的内容有:V-rep机器人仿真,YOLOV3图像识别,强化学习DDPG,UR5机械臂及RG2机械手,Kinect摄像头。 使用环境:Win10,Pytorch0.4,V-rep 整个实验一共由多篇文章组成,本文是第四部分。 第四部分:YOLOV3图像识别 文章目录第四部分:YO...

weixin_42158966的博客 5836

Scala 设计下划线_ 的意义 以及使用。

Scala中是这样定义下划线 _ 的: _ 代表 ‘’任意‘’ 在Scala语言中存在类型推理,就是有的时候你不必指定具体的类型,Scala语言会自动进行推测参数的类型是什么。 比如: var a = "a" 这里Scala会自动推测他为 String类型。 var b = 2 这里Scala会自动推测他为Int类型 那我们在Scala语言...

qq_29499107的博客 631

AI医疗影像诊断工具2025 完整教程

本教程所述工具均为辅助诊断设备,不可替代执业医师判断。部署使用需遵守当地医疗器械管理法规。推荐开源框架组合:代码太多打包上传网盘了 自行下载。2025年的AI医疗影像诊断工具将以。

m0_60084632的博客 2029

高通camera调试经验总结

修改AF对焦模式 adb shell setprop vendor.debug.camera.af.manual 2 //使能手动对焦 adb shell setprop vendor.debug.camera.af.manual 0 //使能自动对焦

weixin_43381364的博客 1万+

Scala Map详解

Scala中Map继承自Iterator特质,是一组(K,V)对偶。其子类SortedMap按照Key排序访问其中的实体。1.可变map和不可变mapscala同时支持可变和不可变map。不可变map从不改变,因此你可以线程安全的共享其引用,在多线程的应用程序中也没问题。举例来说,既有scala.collection.mutalbe.Map,也有scala.collection.immutalbe.

NON blog 6769

深入解析ADC采样电容:从充电误差到LSB精度的关键设计

本文深入解析了ADC采样电容在模数转换中的核心作用,重点探讨了充电时间常数与采样误差的博弈关系。通过推导最小采样时间公式,揭示了精度、速度、源阻抗与内部电容之间的制约关系,并提供了从理论计算到外部驱动电路设计的实战指南,是确保ADC达到LSB精度的关键。

android的专栏 1103

scala之map

7.1 映射 Map-基本介绍 Scala中的Map 和Java类似,也是一个散列表,它存储的内容也是键值对(key-value)映射,Scala中不可变的Map是有序的,可变的Map是无序的。 Scala中,有可变Map (scala.collection.mutable.Map) 和 不可变Map(scala.collection.immutable.Map) 7.2 构建Map 7.2.1 方式1-构造不可变映射 Scala中的不可变Map是有序,构建Map中的元素底...

qq_41458071的博客 821

低功耗设计-ir drop的signoff corner怎么选择?

2.tt的(tt85 是比较接近芯片真实工作情况的);我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧?有要求就用要求的就好,没要求前两种看公司需求。3.signoff文档要求的;有几个方向,看公司需求吧。

m0_61544122的博客 1592

反应堆设计:基于MATLAB的反应堆仿真和分析,包括反应堆稳态分析、反应堆动态分析和反应堆安全分析 介绍

反应堆设计是利用计算机技术对核反应堆进行设计和模拟,以获得安全、高效、经济的核能发电系统。它是核能领域的重要组成部分,在电力生产、核医学、科学研究等领域有着广泛的应用。

走向CTO的路上... 1112

scala中Map集合大全

美图欣赏: 一.背景 映射(map), 也是十分重要的。大好基础,才能一路打boss 二.Map介绍 在Scala中,把哈希表这种数据结构叫做映射。 Scala中的Map存储的内容是键值对(key-value),Scala中不可变的Map是有序的,可变的Map是无序的。 Scala中,有可变Map (scala.collection.mutable.Map) 和 不可变Map(s...

知其然,知其所以然 1万+

AI Agent Harness与SCADA系统集成

简单来说,AI Agent Harness是Industrial AI Agent的“中央调度室+装备库+知识库+安全网”把不同技术栈、不同部署环境(云/边/端)、不同功能(感知、推理、决策、执行、验证)的“零散Agent”组装成具备特定工业场景能力的Agent Team(如聚合反应根因诊断Agent Team);管理Agent Team的生命周期(创建、初始化、调度、监控、销毁);提供统一的工业多工具调用接口(对接SCADA、MES、PLC、DCS、巡检机器人、数字孪生平台等);内置。

欢迎来到我的优快云空间!这里聚焦AI大模型应用实战,分享前沿技术、实战案例与开发经验。 355

Scala 集合 —— Array、Map、Seq、Set

Scala 集合类库很庞大,包括 List,Set,Map,Array等。利用 toList,toSet 和 toArray 方法,各种集合类型可以方便地互相转换。MapScala 的 Map 类没有提供根据内容的键或值排序的方法,当我们可以将 Map 转换为 Scala 的 Seq 类型,而 Seq 支持排序。Scala 的 Seq 类和 Java 的 List 接口类似,都是可迭代集合,即具有确

1万+

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Scala解析Json、JsonMap、并排序

不多哔哔,上代码 import com.google.gson.{Gson, JsonObject} import scala.util.Try val a = "{\"id\":\"1e6d6e19326dc9ef9871390ff0c5b966\",\"items\":{\"26772178\":768.46793983337}}" val b = Try{new Gson().fromJ...

止鱼 1346

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

scala vs java,Scala vs Java,性能和内存?

I am keen to look into Scala, and have one basic question I cant seem to find an answer to:in general, is there a difference in performance and usage of memory between Scala and Java?解决方案Scala makes i...

weixin_32667439的博客 131

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

JsoupBrowser vs HtmlUnitBrowser:Scala Scraper两种浏览器选择指南

Scala Scraper是一个功能强大的Scala库,用于从HTML页面中提取内容。在使用Scala Scraper进行网页抓取时,选择合适的浏览器实现至关重要。本文将详细对比两种主要的浏览器选择:JsoupBrowser和HtmlUnitBrowser,帮助你根据项目需求做出最佳决策。 ## 核心功能概述 Scala Scraper提供了两种浏览器实现,它们各有特点,适用于不同的使用场景:

gitblog_00037的博客 1106

Scala Collection

Scala集合是强大的数据结构,支持可变和不可变类型,包括列表、数组、集合和映射等。不可变集合是默认选择,强调函数式编程特性如map、filter和reduce操作。常用集合如List、Vector、Set和Map各有特点:List适合递归,Vector随机访问高效,Set自动去重,Map快速查找。集合操作涵盖遍历、转换、过滤和聚合,鼓励无副作用编程。实践中需注意性能差异、类型推断和Scala版本兼容性。综合示例展示了如何利用集合进行高效数据处理。

m0_57545130的博客 1158

如何快速掌握Effective Scala:Twitter的Scala编程黄金法则

Scala作为一门强大的函数式与面向对象混合编程语言,在企业级应用开发中越来越受欢迎。然而,Scala语言的灵活性和强大的表达能力也带来了学习曲线陡峭的问题。Twitter的Effective Scala指南正是为了解决这个问题而生,它汇集了Twitter多年在生产环境中使用Scala的经验和最佳实践。 ## 为什么需要Effective Scala指南?🤔 Scala是一门功能丰富的语言,

gitblog_00803的博客 647

scala 集合List Array Seq详解

scala> val l=List(1 to 10:_*) val l: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> val a=Array(1 to 10:_*) val a: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> val s=Seq(1 to 10:_*) val s: Seq[Int] = List(1, 2, 3, 4, 5, 6, 7,

花木兰 1667

Scala基础三

字符串差值 val name = "zhangsan" println("name is:"+name) //这种写法不友好 println(s"name is:$name")//前面加个s ,调用时使用美金符$ 文件操作 val source = Source.fromFile("E://") for (str <- source.getlines()){ pri...

qq_37283909的博客 277

better-monadic-for vs 原生Scala:3个关键场景的代码对比与优势分析

在Scala编程中,`for`推导式是处理集合和 monad 的强大工具,但原生实现中隐式生成的`withFilter`调用常常导致性能损耗和意外行为。**better-monadic-for**(简称bm4)作为一款优化插件,通过重写`for`推导式的解糖逻辑,消除了这些隐式操作,让代码更高效、更可控。本文将通过3个核心场景,对比分析bm4与原生Scala的差异及优势。 ## 场景1:消除隐式

gitblog_00653的博客 469

scala+vs+java+优势_Scala vs Java,性能和内存?

小编典典Scala使得无需意识到即可轻松使用大量内存。这通常非常强大,但有时可能很烦人。例如,假设您有一个字符串数组(称为array),以及从这些字符串到文件的映射(称为mapping)。假设您要获取地图中所有来自长度大于两个的字符串的文件。在Java中,您可能int n = 0;for (String s: array) {if (s.length > 2 && mappi...

weixin_39656686的博客 229

【Scala】一文掌握 Scala 的详细用法(Scala 备忘速查)

Scala官网abstract class D { ... } // 不可创建和模块一样。

数据知道的博客 1万+

scala java8_λ表达式之争:Scala vs Java8

最近几年Lambda表达式风靡于编程界。很多现代编程语言都把它作为函数式编程的基本组成部分。基于JVM的编程语言如Scala、Groovy及Clojure把它作为关键部分集成在语言中。而如今,(最终)Java 8也加入了这个有趣的行列。Lambda表达式最有意思的地方在于,在JVM的角度来看它是完全不可见的。在JVM中没有匿名函数或Lambda表达式的概念。JVM唯一知道是字节码。字节码是一个严格...

weixin_34581086的博客 232

Java 8 vs. Scala(二):Stream vs. Collection

【编者按】在之前文章中,我们介绍了 Java 8和Scala的Lambda表达式对比。在本文,将进行 Hussachai Puripunpinyo Java 和 Scala 对比三部曲的第二部分,主要关注 Stream 和 Collection,本文由 OneAPM 工程师编译整理。首先,为大家做一个简短的介绍,collection 是有限的数据集,而 stream 是数据的序列集,可以是有限的或无

wangpeng198688的专栏 1041
上一篇: A Deeper Look at the Scala Syntax (scala block)
下一篇: Scala - Parentheses and Curly Brackets in Anonymous Functions
DViewer
博客等级 码龄16年 16粉丝 6原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值