Coursera Scala 4-1:函數作為對象
Coursera Scala 4-1:函數作為對象
Functions Types Relate to Classes
Scala是純粹的麵向對象的語言,函數是擁有apply方法的對象。
函數類型A=>B
等價於:
package scala
trait Function1[A,B]{
def apply(x:A):B
}
Functions Values Ralate to Objects
匿名函數
(x:Int) => x*x
等價於:
{ class AnonFun extends Function1[Int, Int] {
def apply(x:Int):Int = x*x
}
new AnonFun
}
更短的寫法:
new Function1[Int, Int] {
def apply(x:Int):Int = x*x
}
函數調用
對於函數調用,如f(a,b),f是class type,函數調用等價於:
f.apply(a,b)
所以,如下寫法:
val f = (x: Int) => x*x
f(7)
轉換成麵向對象形式:
val f = new Function1[Int,Int] {
def apply(x: Int) = x*x
}
f.apply(7)
以上對類型 f 的轉換叫做eta-expansion
eta-expansion
函數調用 例子:
List(1,2)=List.apply(1,2)
object Function{
def apply[T](x:T):T=x
}
Function[Int](1) //> res0: Int = 1
最後更新:2017-04-03 05:39:17