函数作为值传递
| scala> def fun1(field: String,field1: String) = println(s"fun1 field = $field, field1 = $field1") |
| fun1: (field: String, field1: String)Unit |
| |
| scala> def fun2 = fun1 _ |
| fun2: (String, String) => Unit |
| |
| scala> fun2("info1","info2") |
| fun1 field = info1, field1 = info2 |
匿名函数
| scala> def fun3 = (i: Int, j: Int) => println(s"i = $i, j = $j") |
| fun3: (Int, Int) => Unit |
| |
| scala> fun3(1,2) |
| i = 1, j = 2 |
高阶函数 (参数为函数的函数)
| |
| scala> def fun4(name: String, func: (String, String) => Unit): Unit = func(name,name+"1") |
| fun4: (name: String, func: (String, String) => Unit)Unit |
| |
| |
| scala> fun4("abc",(field1: String,field2: String) => println(s"field1 = $field1, field2 = $field2")) |
| field1 = abc, field2 = abc1 |
参数
| |
| scala> def fun(f: () => Unit) = f |
| fun: (f: () => Unit)() => Unit |
| |
| |
| scala> def fun(f: String => Unit) = f |
| fun: (f: String => Unit)String => Unit |
实例
| |
| scala> 1 to 10 |
| res6: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
| |
| |
| scala> Array(1 to 10) |
| res8: Array[scala.collection.immutable.Range.Inclusive] = Array(Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) |
| |
| |
| scala> val arr = Array(1 to 10:_*) |
| arr: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
| |
| |
| scala> arr.map((x: Int) => x + 1) |
| res10: Array[Int] = Array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11) |
| |
| |
| scala> arr.map(x => x + 1) |
| res11: Array[Int] = Array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11) |
| |
| |
| scala> arr.map(_ + 1) |
| res12: Array[Int] = Array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11) |
闭包
函数的变量不在其作用域内被调用,就是闭包的概念
| def funOut(): Unit ={ |
| val num = 10 |
| def funIn(): Unit ={ |
| |
| println(num) |
| } |
| |
| funIn() |
| } |
柯理化
| def main(args: Array[String]): Unit = { |
| |
| fun1(1,2) |
| fun2(1)(2) |
| } |
| |
| |
| def fun1(x: Int, y: Int): Unit ={ |
| println(s"x = $x, y = $y") |
| } |
| |
| |
| def fun2(x: Int) = (y: Int) => println(s"x = $x, y = $y") |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!
· Ai满嘴顺口溜,想考研?浪费我几个小时
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想