Scala Tour

[译]Scala高阶函数

2017-05-04  本文已影响213人  steanxy

Scala允许定义高阶函数。高阶函数以其它函数作为参数,或者其结果是一个函数。下面是函数apply,参数是另一个函数f和一个值v,然后将f应用于v

def apply(f: Int => String, v: Int) = f(v)

注意:如果上下文需要,方法会自动强制作为函数使用。

下面是一个示例:

class Decorator(left: String, right: String) {
  def layout[A](x: A) = left + x.toString() + right
}

object FunTest extends App {
  def apply(f: Int => String, v: Int) = f(v)
  val decorator = new Decorator("[", "]")
  println(apply(decorator.layout, 7))
}

执行后输出为:

[7]

在这个示例中,因为方法apply需要,方法decorator.layout自动强制作为类型为Int => String的值使用。需要注意的是,方法decorator.layout是一个多态方法(这个方法抽象了签名类型),Scala编译器必须先适当实例化其方法类型。

上一篇 下一篇

猜你喜欢

热点阅读