1.定義方法
- 帶參不帶返回值
scala> def main(args: Array[String]) :Unit = {println(args.length)}
main: (args: Array[String])Unit
scala> main(Array("a","b"))
2
scala>
使用Unit其實(shí)也有返回值军熏,只不過(guò)返回值為空:Unit的實(shí)例:()
- 帶參帶返回值
方法的返回值類(lèi)型可以不寫(xiě),編譯器可以推斷出來(lái)年缎,但是對(duì)于遞歸函數(shù)歼争,必須指定返回類(lèi)型
scala> def add(x: Int) : Int = x + 1
add: (x: Int)Int
scala> add(1)
2
scala>
- 無(wú)參無(wú)返回值
scala> def sayHello() :Unit = {println("hello")}
sayHello: ()Unit
scala> sayHello()
hello
scala>
2.定義函數(shù)
- 函數(shù)的定義,在scala中考抄,函數(shù)也是一個(gè)對(duì)象细疚,可以用一個(gè)變量來(lái)引用
scala> var fun = (x: Int) => x * 10
fun: Int => Int = <function1>
function1:表示fun這個(gè)變量的類(lèi)型是function,而且是一個(gè)參數(shù)的函數(shù)
- 函數(shù)的調(diào)用
scala> fun(3)
res: Int = 30
- 匿名函數(shù)
scala> (x: Int, y: Int) => x + y
res29: (Int, Int) => Int = <function2>
scala> res29(2,6)
res30: Int = 8
- scala的函數(shù)與方法的區(qū)別
- 函數(shù)包含
=>
,方法的定義使用:def
- 函數(shù)是可以作為參數(shù)傳入方法里面的的座泳,而方法是不可以作為參數(shù)的
- eg:arr數(shù)組調(diào)用map方法惠昔,傳入(x: Int) => x10匿名函數(shù)將數(shù)組中的每個(gè)元素執(zhí)行10操作
scala> val arr = Array(1,2,3,4,5)
arr: Array[Int] = Array(1,2,3,4,5)
scala> arr.map((x: Int) => x*10)
res31: Array[Int] = Array(10,20,30,40,50)
scala> arr.map(x => x*10)
res32: Array[Int] = Array(10,20,30,40,50)
scala> arr.map(_*10)
res33: Array[Int] = Array(10,20,30,40,50)
- 函數(shù)的變體
scala> var f: Int => Int = {x => x * x}
f: Int => Int = <funtion1>
解析: 定義一個(gè)函數(shù)f,接受一個(gè)int類(lèi)型的參數(shù),返回值為int挑势。 函數(shù)的實(shí)現(xiàn)為{x => x*x}
3.將方法轉(zhuǎn)換成函數(shù)
定義一個(gè)函數(shù)myFun镇防,參數(shù)為一個(gè)方法(f: Int => Int)Unit
,傳入方法f0.
scala> def myFun(f: Int => Int){
printfln(f(100))
}
myFun: (f: Int => Int)Unit
scala> val f0 = (x: Int) => x*x
f0: Int => Int = <function1>
scala> myFun(f0)
10000
在定義一個(gè)方法f1.不能把一個(gè)方法當(dāng)做參數(shù)傳入另外一個(gè)方法潮饱,只能把一個(gè)方法的方法名當(dāng)做參數(shù)来氧,傳入到另外一個(gè)方法中,如果在一個(gè)方法中傳入方法名香拉,會(huì)將方法名轉(zhuǎn)換成一個(gè)函數(shù)
scala> def f1(x: Int) = x*x
f1: (x:Int)Int
scala> f1(4)
res34: Int = 16
scala> myFun(f1(4))
<console>:11: error: type mismatch;
found :Int
required :Int => Int
scala> myFun(f1)
10000
scala> f1 _
res35: Int => Int = <function1>
scala> myFun(f1 _)
10000
scala> myFun(x => f1(x))
10000