Scala学习笔记(三)—— 方法和函数

时间:2023-03-09 17:51:10
Scala学习笔记(三)—— 方法和函数

1. 方法

方法使用 def 定义:

def 方法名(参数名:参数列表,…) :返回值类型 = { 方法结构体 }

 scala> def add(x : Int ,y : Int):Int = x+y
add: (x: Int, y: Int)Int // 返回值可以省略,Scala编译器可以通过值的类型推断出变量的类型
scala> def subtract(x : Int,y : Double) = x-y
subtract: (x: Int, y: Double)Double // 当返回值为空时,可以省略,也可以写为Unit,类似与Java的void
scala> def printMulti(x : Int ,y :Int): Unit = println(x * y)
printMulti: (x: Int, y: Int)Unit

抽象方法

 abstract class Test{

   //  没有方法体的方法为抽象的,包含它的类型于是也是一个抽象类型
def add(x : Int,y : Int)
}

ps:对于递归方法,必须指定返回类型

2. 函数

Scala的函数是基于Function家族,0-22,一共23个Function Trait可以被使用,数字代表了Funtcion的入参个数

 // 函数的定义
val add = new Function2[Int,Int,Int] {
override def apply(x: Int, y: Int): Int = x+y
} // 函数的定义简写
val subtract = (x :Int,y:Int) => x-y

方法转为函数:

 // 定义一个方法
scala> def add(x:Int,y:Int) =x+y
add: (x: Int, y: Int)Int // 将该方法转为函数
scala> add _
res9: (Int, Int) => Int = <function2>

3. 方法和函数的区别

https://blog.csdn.net/u010839779/article/details/80849607