scala 模式匹配

复制代码
https://blog.csdn.net/bluishglc/article/details/50995939


scala> val a = Array(1,2,3,4) a: Array[Int] = Array(1, 2, 3, 4)

匿名函数,由繁入简,

 使用case语句构造匿名函数的“额外”好处,

 case语句(组合)除了可以被编译为匿名函数(类型是FunctionX,在Scala里,所有的函数字面量都是一个对象,这个对象的类型是FunctionX),还可以非常方便的编译为一个偏函数PartialFunction!(注意:PartialFunction同时是Function1的子类)编译器会根据调用处的函数类型声明自动帮我们判定如何编译这个case语句(组合)

 case语句声明的变量就是偏函数的参数,既然case语句只能声明一个变量,那么偏函数受限于此,也只能有一个参数!


scala> a.map(x => x match {
     |   case 0 => "zero"
     |   case 1 => "one"
     |   case 2 => "two"
     |   case _ => "other"
     | })
res2: Array[String] = Array(one, two, other, other)


scala> a.map(x => x match { case x => x })
res4: Array[Int] = Array(1, 2, 3, 4)



scala> a.map(case x => x)
<console>:1: error: illegal start of simple expression
a.map(case x => x)
      ^


scala> a.map{case x => x}
res3: Array[Int] = Array(1, 2, 3, 4)


scala> a.map{x => x}
res7: Array[Int] = Array(1, 2, 3, 4)
复制代码

 

posted on   TMatrix52  阅读(146)  评论(0编辑  收藏  举报

编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示