14.2 作为值的函数

在 Scala 中, 函数是一等公民.

所以, 函数也可以像数字一样, 存储在变量中.

package com.atguigu.day12

object ValDemo1 {
  def main(args: Array[String]): Unit = {
    // fun存放 isOdd这个函数
    // 后面的下划线表示: 我们确实是想用 fun 来存放函数, 而不是在调用这个函数
    // 现在 fun和isOdd是完全等价的
    val fun = isOdd _
    println(fun(11))
    println(isOdd(11))
  }
  def isOdd(x: Int): Boolean = x % 2 == 1
}

我们可以对函数做两件事情:

  1. 调用它

  2. 传递它:

    • 把它存放在变量中
    • 作为参数传递给另外一个函数
Copyright © 尚硅谷大数据 2019 all right reserved,powered by Gitbook
该文件最后修订时间: 2018-12-13 15:12:29

results matching ""

    No results matching ""