阅读860 返回首页    go 阿里云 go 技术社区[云栖]


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

  上一篇:go Linux php/php-fpm 安装,配置
  下一篇:go 2015火车票抢票,放票时间,几点放票