Scala 高阶函数

一、函数作为参数

  highOrderFunc是一个高阶函数,因为它可以接收一个函数作为参数

object PartialFunctionDemo {

  def main(args: Array[String]): Unit = {
    val add = (d: Double) => d + 1
    
    val res = highOrderFunc(add, 5)
    println(res)
    
  }

  def highOrderFunc(f: Double => Double, p: Double) = f(p)

}

  

二、函数作为返回值

  函数f接收一个参数n,返回一个函数(x: Double) => n - x

  f(5)(8),f(5)的返回值是一个函数,(8)是上一步返回函数的参数

def main(args: Array[String]): Unit = {
  val f = (n: Double) => (x: Double) => n - x

  val res = f(5)(8)
  println(res) // -3

}

  

猜你喜欢

转载自www.cnblogs.com/noyouth/p/12817984.html