Scala方法定義,方法和函式的區別,將方法轉換成函式
阿新 • • 發佈:2018-12-25
1. 定義方法和函式
1.1. 定義方法
方法的返回值型別可以不寫,編譯器可以自動推斷出來,但是對於遞迴函式,必須指定返回型別
1.2. 定義函式
1.3.方法和函式的區別
在函數語言程式設計語言中,函式是“頭等公民”,它可以像任何其他資料型別一樣被傳遞和操作
案例:首先定義一個方法,再定義一個函式,然後將函式傳遞到方法裡面
package cn.toto.scala
/**
* Created by toto on 2017/6/27.
*/
object MethodAndFunctionDemo {
//定義一個方法
//方法m2引數要求是一個函式,函式的引數必須是兩個Int型別
//返回值型別也是Int型別
def m1(f:(Int,Int) => Int) : Int = {
f(2,6)
}
//定義一個函式f1,引數是兩個Int型別,返回值是一個Int型別
val f1 = (x:Int,y:Int) => x + y
//再定義一個函式f2
val f2 = (m:Int,n:Int) => m * n
//main方法
def main(args: Array[String]): Unit = {
//呼叫m1方法,並傳入f1函式
val r1 = m1(f1)
println(r1)
//呼叫m1方法,並傳入f2函式
val r2 = m1(f2)
println(r2)
}
}
執行結果:
8
12
1.2. 將方法轉換成函式(神奇的下劃線)
程式碼如下:
package cn.toto.scala
/**
* Created by toto on 2017/6/27.
*/
object TestMap {
def ttt(f:Int => Int):Unit = {
val r = f(10)
println(r)
}
val f0 = (x : Int) => x * x
//定義了一個方法
def m0(x:Int) : Int = {
//傳遞進來的引數乘以10
x * 10
}
//將方法轉換成函式,利用了神奇的下滑線
val f1 = m0 _
def main(args: Array[String]): Unit = {
ttt(f0)
//通過m0 _將方法轉化成函式
ttt(m0 _);
//如果直接傳遞的是方法名稱,scala相當於是把方法轉成了函式
ttt(m0)
//通過x => m0(x)的方式將方法轉化成函式,這個函式是一個匿名函式,等價:(x:Int) => m0(x)
ttt(x => m0(x))
}
}