函数参数的使用

46 阅读1分钟
object Base42 {
  /*
   * 函数参数的使用
   */
  def hello(name: String = "小明", age: Int = 17, gender: String = "女"): Unit = {
    println(s"hello,我是${name}${age}岁,性别:${gender}")
  }

  def main(args: Array[String]): Unit = {
    hello("小花", 18, "女")
    hello("小明", 19, "男")
    hello("小花", 18) // 1. 不写性别,默认为女
    hello()           // 2. 不写所有参数,全部使用默认值
  
   hello(age=18)
   hello(gender="男",name="小李")

  }
}

允许参数的个数不同,类型相同

变参:参数类型后边,加一个*

object Base43 {
 
  def getSum(args: Int*): Int = {
    // [1,2,3,4]
    var sum = 0
    for (i <- args) {
      sum += i
    }
    sum
  }

  def main(args: Array[String]): Unit = {
    val result1 = getSum(1)
    val result2 = getSum(4, 1, 2, 3, 5)
    println(result1, result2)
  }
}