/**
* Scala 方法与函数
* Scala 有方法与函数,二者在语义上的区别很小。Scala 方法是类的一部分,而函数是一个对象可以赋值给一个变量。换句话来说在类中定义的函数即是方法
*/
object sayHello { def main(args: Array[String]): Unit = { sayHello("yexj")
printf("\n")
sayHello("yexj", "ben", "fox")
printf("\n")
// 带名参数,可以与不带名的混合使用,也可以调整顺序
sayHello("yxj", lastName = "llast", middleName = "midd")
printf("\n") // 变长参数的使用
val s = sum(1, 2, 4, 5, 6, 7, 8, 9, 34, 3, 2)
printf("the sum is %d", s) printf("\n") // 使用下面这种序列调用函数是不行的,报错
// sum(1 to 5)
// 需要使用到scala特殊的语法,具体为:
val s1 = sum(1 to 5: _*)
printf("the s1 =" + s1)
} // 函数参数
def sayHello(name: String) = {
printf("hello %s,how are you?", name)
name
} // 参数的返回值,不用return,最后的age就是函数返回值,scala会推断出返回值类型
def sayHello(name: String, age: Int) = {
printf("hi %s,your age is %d", name, age)
age
} /**
* 参数带有默认值的
*
* @param firstName
* @param middleName
* @param lastName
*/
def sayHello(firstName: String, middleName: String = "-", lastName: String = "Jerry") = {
printf("firstName=" + firstName + ",middleName=" + middleName + ",lastName=" + lastName)
} /**
* 变长参数,不确定具体有多少个入参值
*
* @param nums
*/
def sum(nums: Int*) = {
var result = 0;
for (num <- nums) {
result += num;
}
result
} }