Scala函数的声明和使用
知识点:
-
定义一个scala函数的基本结构: def 函数名(参数列表):函数的返回值={方法体代码}
-
通用规则:scala会将方法体最后一行代码作为返回值返回,不需要加return关键字
-
通用规则:如果方法体只有一行代码,则方法体{}可以省略
-
函数默认的访问权限是public,此外也可以通过private,protected来修饰访问权限
-
函数前可以用override,final来修饰
-
scala可以根据函数的返回值自动推断出函数的返回值类型
-
注意:如果函数和方法体之间没有=,则函数的返回值类型一律为Unit(空类型)
-
scala函数支持默认参数机制,形式:
def 函数名(形参名:参数类型=默认值)={}
注意,默认值的类型要和形参类型一致 -
scala函数支持可变参数,类比于java的变长参数。形式:
def 函数名(形参名:参数类型*)={}
可变参数底层会被封装为一个集合,可以通过集合相关的操作进行操作
注意:可变参数必须位于参数列表的最后
object Demo07 {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
def f1(a:Int,b:Int):Int={
a+b
} //> f1: (a: Int, b: Int)Int
def f2(a:Int,b:Int):Int=a+b //> f2: (a: Int, b: Int)Int
//函数调用
f1(2,3) //> res0: Int = 5
def f3(a:Int,b:Int)={
a+b
} //> f3: (a: Int, b: Int)Int
def f4(a:String,b:Int)={
a*b
} //> f4: (a: String, b: Int)String
f4("hello",2) //> res1: String = hellohello
def f5(a:String)={
a.split(",")
} //> f5: (a: String)Array[String]
f5("hello,world") //> res2: Array[String] = Array(hello, world)
def f6(a:String){
a.split(",")
} //> f6: (a: String)Unit
//练习1:定义一个函数 f7,接收一个整型数字n,打印从0~n的所有数字
def f7(n:Int)={
for(i<-0 to n){
println(i)
}
} //> f7: (n: Int)Unit
f7(3) //> 0
//| 1
//| 2
//| 3
//scala的默认参数机制
def f8(a:String,b:String="2002")={
//返回两字符串拼接的结果
a+b
} //> f8: (a: String, b: String)String
f8("hello","world") //> res3: String = helloworld
//scala的可变参数
def f9(a:String,num:String*)={
for(i<-num){
println(i)
}
} //> f9: (a: String, num: String*)Unit
f9("hello","world") //> world
}