函数定义
//推荐使用
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
//无参函数
scala> val fun = () =>println("123")
fun: () => Unit = <function0>
方法和函数的区别:
1.定义语法不同
2.方法一般定义在类,特质或者object中,
3.方法可以共享所在的类,特质,或者object中的属性
4.方法可以调用函数
联系
(1)可以把函数作为参数传递给方法
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)方法可以转换成函数
a.把一个方法作为参数传递给其他方法或者函数
b.通过下划线做转换 方法名 _
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
网友评论