object fwh25 {
/*
* 函数参数的使用
*/
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. 不写所有参数,全部使用默认值
}
}
输出结果
object fwh26 {
// 允许参数的个数不同,类型相同
// 变参:参数类型后边,加一个*
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)
}
}
输出结果
若结果并非所愿
那就在尘埃落定前奋力一博
失败曾令人想要逃离 但绝境重生,方为宿命