1.方法定義用def,函式的引數 要寫型別,不寫型別不可以。
2.函式的返回值型別可以不寫,會自動推斷
3.scala會將函式體中最後一行計算的結果當做返回值返回
4.可以寫「return」,寫了return要顯式的宣告方法體的返回型別。
5.定義方法時,如果不寫「=」,那麼無論方法體中最後一行計算的結果返回是什麼,都會被丟棄,返回unit
6.方法體可以一行搞定,那麼方法體的「 」 可以省略不寫
def max(x:int,y:int) =view codeelse
}println(max(100,2))
def max(x:int,y:int) = if(x>y) x else
y println(max(100,2))
遞迴函式要顯式的宣告返回型別
def fun(x:int):int =view codeelse
}println(fun(5))
def fun(x:int=100,y:int=200) = x+yprintln(fun(y=80))
def fun(s:string*)=)}fun("hello","a","b","c")
val fun: (int, int) => int = (x:int,y:int)=>偏應用函式是乙個表示式,將方法中不變的引數寫上,變化的引數使用「_」表示,下次直接呼叫這個偏應用表示式直接傳入變化的引數就可以println(fun(10,20))
def showlog(date:date,log:string) =val date = new
date()
showlog(date,"a")
showlog(date,"b")
showlog(date,"c")
val fun =showlog(date,_:string)
fun("aaa")
fun("bbb")
fun("ccc")
def fun(x:int) =1.函式的引數是函式else
}fun1(x)
}println(fun(5))
2.函式的返回是函式 --函式的返回是函式時,要顯式宣告函式的返回型別
3.函式的引數和返回都是函式
//view code函式的引數是函式
def fun1(f:(int,int)=>int,s:string):string =
val result = fun1((a:int,b:int)=>,"hello")
println(result)
//函式的返回是函式
def fun(a:int,b:int) :(string,string)=>string =
fun1
}println(fun(10,20)("hello","world"))//
hello@world#200
//函式的引數和返回都是函式
def fun(f:(int,int)=>int) :(string,string)=>string=
fun1
}println(fun((a:int,b:int)=>)("hello","world"))
柯里化函式就是高階函式的簡化版
def fun(a:int,b:int)(c:int,d:int) =println( fun(1,2)(3,4))
scala中的函式
在scala中定義函式,需要給出 函式名 引數 函式體。例如 def abs x double if x 0 x else x 如果有引數,必須要給出引數型別。如果函式不是遞迴的,返回值型別就可以不寫。scala編譯器自帶型別推導功能。如果函式體由多個表示式組成,可以用 塊的方式來組織,比如 def...
Scala中的高階函式
1.在變數中存放函式 1 定義函式fun1 2 將函式賦給乙個變數 注意函式名和下劃線之間有空格 3 呼叫這個函式 2.匿名函式 匿名函式沒有函式名,將函式賦給變數fun2。函式的引數是string型別,返回unit型別 3.高階函式 1 函式的引數為函式的高階函式 a 函式的第乙個引數是func函...
scala中的偏函式
case語句 組合 除了可以被編譯為匿名函式 型別是functionx,在scala裡,所有的函式字面量都是乙個物件,這個物件的型別是functionx 還可以非常方便的編譯為乙個偏函式partialfunction!注意 partialfunction同時是function1的子類 編譯器會根據呼...