一、函数参数的默认值
格式: def 函数名(参数1:类型1=默认值1,参数2:类型2=默认值2)
def greet(name: String = "Guest", age: Int = 18): Unit = {
println(s"Hello, $name! You are $age years old.")
}
// 使用默认值
greet() // 输出: Hello, Guest! You are 18 years old.
greet("小花")
greet(19)
greet(age=19)
// 只提供一个参数
greet(name = "Alice") // 输出: Hello, Alice! You are 18 years old.
// 提供所有参数
greet(name = "Bob", age = 25) // 输出: Hello, Bob! You are 25 years old.
二、创建不带()的方法
如果函数没有参数,可以省略定义函数时的( )
格式:def 方法名:[返回类型] = {}。
def sayHello: Unit = {
println("hello")
}
sayHello // 不用加()
三、可变参数(创建接受变参的方法)
问题:如何定义一个函数,它能接收数量不定的参数,并计算它们的累加?
// 可变参数 用来接受同一类型的多个参数
// 格式:参数类型*
// 要点:
// 1.类型要一致
// 2.可变参数必须在列表的最后
def getSum(args:Int*): Int = {
var sum = 0
for(i <- args) {
sum += i
}
sum
}
def main(args: Array[String]): Unit = {
val rst1 = getSum(1,2,3) // 6
val rst2 = getSum(1,2,3,4) // 10
val rst3 = getSum(1,2) // 3
println(rst1,rst2,rst3)
}