函數(shù)定義
//推薦使用
scala> val fun = (x:Int,y:Int) => x+y
fun: (Int, Int) => Int = <function2>
scala> fun(1,3)
res62: Int = 4
scala> val funs = (_:Int)+(_:Int)
funs: (Int, Int) => Int = <function2>
scala> funs(1,2)
res63: Int = 3
scala> val fun = (x:Int,y:Int)=>if(x<y)x else y
fun: (Int, Int) => Int = <function2>
scala> fun(3,2)
res69: Int = 2
//無參函數(shù)
scala> val fun = () =>println("123")
fun: () => Unit = <function0>
方法和函數(shù)的區(qū)別:
1.定義語法不同
2.方法一般定義在類啊送,特質(zhì)或者object中,
3.方法可以共享所在的類馋没,特質(zhì),或者object中的屬性
4.方法可以調(diào)用函數(shù)
聯(lián)系
(1)可以把函數(shù)作為參數(shù)傳遞給方法
scala> def m(f:(Int,Int)=>Int) = f(2,3)
m: (f: (Int, Int) => Int)Int
scala> val f = (x:Int,y:Int) => x+y
f: (Int, Int) => Int = <function2>
scala> m(f)
res74: Int = 5
(2)方法可以轉(zhuǎn)換成函數(shù)
a.把一個(gè)方法作為參數(shù)傳遞給其他方法或者函數(shù)
b.通過下劃線做轉(zhuǎn)換 方法名 _
scala> def m2(x:Int,y:Int) = x- y
m2: (x: Int, y: Int)Int
scala> m(m2)
res75: Int = -1
scala> m2 _
res76: (Int, Int) => Int = <function2>
scala> m(m2 _)
res77: Int = -1