学习scala笔记--3 函数初步

 

 

 

函数定义

 

函数最后一行的的返回值就是函数的返回值 

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

 

 

----------------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值