函数定义
函数最后一行的的返回值就是函数的返回值
scala> :paste
// Entering paste mode (ctrl-D to finish)
def hello(name:String,age:Int)={
println(" hello "+name+" your age is "+age)
"hello "+name
}
println(hello("catlina",100))
// Exiting paste mode, now interpreting.
hello catlina your age is 100
hello catlina
hello: (name: String, age: Int)String
----------------------------------
不谢后面的 = 是没有返回值的
scala> :paste
// Entering paste mode (ctrl-D to finish)
def hello2(name:String,age:Int) {
println(" hello "+name+" your age is "+age)
"hello "+name
}
println(hello2("catlina2",100))
// Exiting paste mode, now interpreting.
hello catlina2 your age is 100
()
hello2: (name: String, age: Int)Unit
----------------------------------
单行函数 可以没有花括号
scala> def haha(name:String)=print("haha "+name)
haha: (name: String)Unit
scala> haha("kafka")
haha kafka
----------------------------------
默认参数
scala> :paste
// Entering paste mode (ctrl-D to finish)
def helloFunc(name:String,age:Int = 20) = {
println(" hello "+name+" your age is "+age)
}
helloFunc("java")
// Exiting paste mode, now interpreting.
hello java your age is 20
helloFunc: (name: String, age: Int)Unit
----------------------------------
命名参数 可以不按照定义顺序传参
scala> helloFunc(age=100 ,name="hadoop")
hello hadoop your age is 100
----------------------------------
可变参数 -使用*
scala> def sum(num : Int*)={ var ret =0 ; for(x<- num){ ret= ret+ x} ;ret}
sum: (num: Int*)Int
scala> sum(1,2,3,4,5,6,7,8,9,10)
res38: Int = 55
----------------------------------
要传递序列 注意语法
scala> sum(1 to 10 :_*)
res39: Int = 55
----------------------------------