【Scala入门学习】Scala的方法和函数

ops/2024/9/23 0:24:19/

1. 方法

scala中的操作符都被当成方法存在,比如说+、-、*、/

1+2就是1.+(2)的调用,

2.0 是doule类型,强调用Int类型的写法为1.+(2:Int)

1.1 方法的声明和使用

定义方法的语法:

def 方法名([变量:变量类型,变量:变量类型]):返回值类型={方法体}

其中:

scala 中,方法里面的最后一个表达式的值就是方法的返回值,不需要return 返回;

示例:

定义无参无返回值的方法:

// 定义无参无返回值的方法
scala> def say():Unit = {println("say hello")}
say: ()Unit
scala> say()
say hello
// 简化过程
scala> def say():Unit = {println("say hello")}
say: ()Unit
// 方法体有一个语句,省略{}
scala> def say():Unit = println("say hello")
say: ()Unit
// 方法返回值可以由方法体返回结果类型推测
scala> def say() = println("say hello")        
say: ()Unit
// 方法形参列表是空, 可省略()
scala> def say = println("say hello")
say: Unit
scala> say
say hello
scala> say()
<console>:13: error: Unit does not take parameterssay()
// 带有返回值的方法
def add(a:Int, b:Int):Int={val c = a + b; return c}

定义带有有参有返回值方法:

// 定义带有有参有返回值方法
scala> def add(a:Int, b:Int):Int={val c = a + b; return c}
add: (a: Int, b: Int)Int
scala> add(4,5)
res8: Int = 9
// 简化流程
scala> def add(a:Int, b:Int):Int={val c = a + b; return c}
add: (a: Int, b: Int)Int
// scala 不建议用return返回方法结果,默认最后一个就是方法的返回值
scala> def add(a:Int, b:Int):Int={val c = a + b; c}
add: (a: Int, b: Int)Int
// 去掉中间变量c
scala> def add(a:Int, b:Int):Int={a + b}
add: (a: Int, b: Int)Int
// 方法体有一个语句,省略{}
scala> def add(a:Int, b:Int):Int=a + b
add: (a: Int, b: Int)Int
// 方法返回值可以由方法体返回结果类型推测
scala> def add(a:Int, b:Int)=a + b
add: (a: Int, b: Int)Int
scala> add(4,5)
res9: Int = 9

方法的调用:

object M1 {def say(name:String) = {println(s"say ${name}")}def add(a:Int, b:Int) = a + bdef main(args: Array[String]): Unit = {// 普通调用M1.say("hainiu")// 中缀方法调用M1 say "hainiu"// 大括号调用,当只有一个入参时才能用M1 say {"hainiu"}M1.add(4,5)// 中缀方法调用M1 add (4,5)}
}

递归方法必须加返回值类型

scala> def calculate(number:Int):Int = {| if(number == 1)| 1| else| number*calculate(number-1)| }
calculate: (number: Int)Intscala> calculate(5)
res14: Int = 120//文件夹递归方式查询def listFiles(path:String):Unit = {val file = new File(path)if(file.isFile){println(file.getPath)}else{println(file.getPath)val list = file.list()for(p<-list){listFiles(path+"/"+p)}}}

可变参数

scala> def sum(x:Int*)={| var sum = 0| for(i<-x)| sum += i| sum| }
sum: (x: Int*)Intscala> sum(1,2,3)
res15: Int = 6scala> sum(1,2,3,4,5)
res16: Int = 15scala> def sum(x:Int,y:Int*)={| var sum = 0| for(i<-y)| sum += i| x * sum| }
sum: (x: Int, y: Int*)Intscala> sum(2,1,2,3)

2. 函数

在 java 中方法和函数是一个意思,在 scala 中方法和函数是两种含义。

方法:属于类或对象的成员

函数:是对象

scala 中,函数是一等公民。可以在任何地方定义,在函数内或函数外,可以作为函数的参数和返回值;函数还可以赋给变量。

函数声明:

val 变量名:[变量类型1,变量类型2 => 函数体返回类型 ] = ([变量:变量类型,变量:变量类型]) => 函数体

示例:

// 函数本身是没有名字的--匿名函数
// function2 是 函数有 两个输入参数 和 一个输出, 本例是 两个Int输入,一个Int输出
scala> (a:Int, b:Int) => a + b
res10: (Int, Int) => Int = <function2>
scala> res10(4,5)
res11: Int = 9
// 把匿名函数赋给变量,这个变量名称就成了函数名称
scala> val add:(Int,Int)=>Int = (a:Int, b:Int) => a + b
add: (Int, Int) => Int = <function2>
scala> add(4,5)
res12: Int = 9

函数的结果做为方法的参数:

示例

// 定义周长函数
val perimeter = (a:Int,b:Int) => (a+b) *2
// 定义面积函数
val area = (a:Int, b:Int) => a*b
// 定义求和方法
def add(a:Int, b:Int) = a+b
// 计算长方形周长和面积的和
println(add(perimeter(4,5), area(4,5)))

函数作为参数和返回值:

scala> add2
res22: (Int, Int) => Int = $Lambda$1133/801476373@59919f37scala> val add = add2
add: (Int, Int) => Int = $Lambda$1133/801476373@59919f37scala> add(100,200)
res23: Int = 300scala> def calculate(x:Int,y:Int) = x+y
calculate: (x: Int, y: Int)Intscala> def calculate(x:Int,y:Int,f:(Int,Int)=>Int) = f(x,y)
calculate: (x: Int, y: Int, f: (Int, Int) => Int)Intscala> calculate(10,20,add)
res24: Int = 30scala> def sub(a:Int,b:Int) = a-b
sub: (a: Int, b: Int)Intscala> val sub = (a:Int,b:Int) => a-b
sub: (Int, Int) => Int = $Lambda$1137/1087688958@784ceacbscala> calculate(1,2,sub)
res25: Int = -1scala> def getFunc() = {| val func = (x:Int,y:Int) => x+y| func| }
getFunc: ()(Int, Int) => Intscala> getFunc()(1,2)
res26: Int = 3scala> def getFunc(a:Int,b:Int) = {| val func = (x:Int) => a*x +b| func| }
getFunc: (a: Int, b: Int)Int => Intscala> getFunc(2,1)(10)
res27: Int = 21

匿名函数

scala> def calculate(x:Int,y:Int) = x+y
calculate: (x: Int, y: Int)Intscala> def calculate(x:Int,y:Int,f:(Int,Int)=>Int) = f(x,y)
calculate: (x: Int, y: Int, f: (Int, Int) => Int)Intscala> val add = (x:Int,y:Int) => x+y
add: (Int, Int) => Int = $Lambda$1044/989321301@77049094scala> calculate(10,20,add)
res9: Int = 30scala> calculate(10,20,(x:Int,y:Int)=> x+y)
res10: Int = 30scala> (x:Int,y:Int) => x+y
res11: (Int, Int) => Int = $Lambda$1068/1578712821@106c988scala> res11(200,300)
res12: Int = 500scala> calculate(10,20,(x,y)=>x+y)
res13: Int = 30scala> (x,y)=> x+y
<console>:1: error: ';' expected but '=>' found.(x,y)=> x+y^

方法转换成函数

1)用空格下划线的方式

# 定义方法def add_def(a:Int,b:Int) = a + b# 方法转函数,用空格下划线的方式val add_func = add_def<空格>_

2)也可以把方法当参数使用,这也因为scala会隐式的把方法转换成函数,但并不是直接支持方法当参数的模式,只是做了隐式的转换,这种函数的转换分两种显示用空格_和隐式的,这也体现了scala灵活的地方。

cala> def add(x:Int,y:Int) = x+y
add: (x: Int, y: Int)Intscala> add 
<console>:13: error: missing argument list for method add
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `add _` or `add(_,_)` instead of `add`.add^
scala> add _
res16: (Int, Int) => Int = $Lambda$1076/287628665@335cdd2scala> calculate(1,2,add _)
res17: Int = 3scala> calculate(1,2,add)
res18: Int = 3

http://www.ppmy.cn/ops/113955.html

相关文章

YOLOv8改进 | 自定义数据集训练 | AirNet助力YOLOv8检测

目录 一、本文介绍 二、AirNet原理介绍 2.1 对比基降解编码器&#xff08;CBDE&#xff09; 2.2 降解引导修复网络&#xff08;DGRN&#xff09; 三、yolov8与AirNet结合修改教程 3.1 核心代码文件的创建与添加 3.1.1 AirNet.py文件添加 3.1.2 __init__.py文件添加 3…

携手阿里云CEN:共创SD-WAN融合广域网

在9月19日举行的阿里云云栖大会上&#xff0c;犀思云作为SD-WAN领域的杰出代表及阿里云的SD-WAN重要合作伙伴&#xff0c;携手阿里云共同推出了创新的企业上云方案——Fusion WAN智连阿里云解决方案。这一创新方案不仅彰显了犀思云在SD-WAN技术领域的深厚积累&#xff0c;更体现…

Java项目: 基于SpringBoot+mybatis+maven服装生产管理系统(含源码+数据库+任务书+开题报告+毕业论文)

一、项目简介 本项目是一套基于SpringBootmybatismaven服装生产管理系统 包含&#xff1a;项目源码、数据库脚本等&#xff0c;该项目附带全部源码可作为毕设使用。 项目都经过严格调试&#xff0c;eclipse或者idea 确保可以运行&#xff01; 该系统功能完善、界面美观、操作简…

SWC(Speedy Web Compiler)

概述 SWC 由 Rust 编写&#xff0c; 既可用于编译&#xff0c;也可用于打包。 对于编译&#xff0c;它使用现代 JavaScript 功能获取 JavaScript / TypeScript 文件并输出所有主流浏览器支持的有效代码。 SWC在单线程上比 Babel 快 20 倍&#xff0c;在四核上快 70 倍。 简…

C#_封装详解

封装 封装 被定义为"把一个或多个项目封闭在一个物理的或者逻辑的包中"。在面向对象程序设计方法论中&#xff0c;封装是为了防止对实现细节的访问。 抽象和封装是面向对象程序设计的相关特性。抽象允许相关信息可视化&#xff0c;封装则使程序员实现所需级别的抽象…

Golang | Leetcode Golang题解之第414题第三大的数

题目&#xff1a; 题解&#xff1a; func thirdMax(nums []int) int {var a, b, c *intfor _, num : range nums {num : numif a nil || num > *a {a, b, c &num, a, b} else if *a > num && (b nil || num > *b) {b, c &num, b} else if b ! ni…

【图像匹配】基于Harris算法的图像匹配,matlab实现

博主简介&#xff1a;matlab图像代码项目合作&#xff08;扣扣&#xff1a;3249726188&#xff09; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 本次案例是基于基于Harris算法的图像匹配&#xff0c;用matlab实现。 一、案例背景和算法介绍 …

Docker_启动redis,容易一启动就停掉

现象以及排查过程 最近在使用docker来搭建redis服务&#xff0c;但是在启动redis哨兵容器时&#xff0c;总是发现这个容器启动后立马就停止了。首先想到的是不是服务器资源不够用了导致的这个现象&#xff0c;排查后发现不是资源问题。再者猜测是不是启动报错了&#xff0c;查看…