函数参数的默认值
def 函数名(参数1:类型1=默认值1,参数2:类型2=默认值2)
(例)定义一个函数,并使用不同的参数来测试使用
object base41 {
def hello(name:String="小明",age:Int=17,gender:String="女")={
println(s"hello,我是${name},${age}岁,性别:${gender}")
}
def main(args:Array[String]):Unit={
hello("小花",18,"女")
hello("小明",18,"男")
hello("小路",18)
hello()
hello(age=18)
hello(gender="男",age=18)
}
}
创建不带()的方法
def 方法名:[返回类型]={}
(例)
def sayHello: Unit = {
println("hello")
}
sayHello
创建接受变参的方法
(例)
// 计算参数的个数和·类型相同
// 函数调用返回值的类型是Int,每一个
// 参数都是Int类型,返回一个
def getSum(args: Int*): Int = {
var sum = 0
for (i <- args) {
sum += i
}
sum
}
def main(args: Array[String]): Unit = {
val result1 = getSum()
val result2 = getSum(1, 2, 3)
println(result1, result2)
}