当前位置: 首页 > news >正文

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

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.lryc.cn/news/439045.html

相关文章:

  • 【JVM】概述
  • 鸿蒙开发笔记_电商严选02_登录页面跳转到我的页面、并传值
  • clip论文阅读(Learning Transferable Visual Models From Natural Language Supervision)
  • 用于图像分割的协 SMA Transformer:同多注意力转换器 !
  • lodash中_.difference如何过滤数组
  • 关于C# 数据库访问 转为 C++ CLI 数据库访问
  • 百度移动刷下拉词工具:快速出下拉词的技术分析
  • 学习笔记-Golang中的Context
  • ArrayList 源码解析
  • libgit2编译
  • mac新手入门(快捷键)
  • curl 的使用详解
  • 从基础到进阶:利用EasyCVR安防视频汇聚平台实现高效视频监控系统的五步走
  • CORS漏洞及其防御措施:保护Web应用免受攻击
  • C语言自定义类型结构体(24)
  • 补题篇--codeforces
  • 【字幕】恋上数据结构与算法之015动态数组03简单接口的实现
  • 基于2023年网络赛赛题了解OpenCv
  • 你到底更适合买虚拟主机还是服务器?
  • linux手册翻译 addr2line
  • python-素数中的等差数列
  • Unity3D 服务器AStar寻路客户端位置同步显示验证详解
  • 无人机之悬停精度篇
  • 力扣题解2848
  • 电子电气架构---智能汽车应该是怎么样的架构?
  • 无心剑七绝《中秋相思》
  • Python画笔案例-051 绘制赵爽弦图
  • SEGGERS实时系统embOS推出Linux端模拟器
  • HTML + CSS - 网页布局之一般布局浮动布局
  • python定时任务,定时爬取水质和天气