当前位置: 首页 > 文档资料 > Scala 中文文档 >

高阶函数(Higher-Order Functions)

优质
小牛编辑
126浏览
2023-12-01

Scala允许定义higher-order functions 。 这些函数将其他函数作为参数,或者其结果是函数。

尝试下面的示例程序,apply()函数接受另一个函数f和一个值v ,并将函数f应用于v。

例子 (Example)

object Demo {
   def main(args: Array[String]) {
      println( apply( layout, 10) )
   }
   def apply(f: Int => String, v: Int) = f(v)
   def layout[A](x: A) = "[" + x.toString() + "]"
}

将上述程序保存在Demo.scala 。 以下命令用于编译和执行此程序。

Command

\>scalac Demo.scala
\>scala Demo

输出 (Output)

[10]