Scala | Scala函数的声明和使用

Scala函数的声明和使用

知识点:
  1. 定义一个scala函数的基本结构: def 函数名(参数列表):函数的返回值={方法体代码}

  2. 通用规则:scala会将方法体最后一行代码作为返回值返回,不需要加return关键字

  3. 通用规则:如果方法体只有一行代码,则方法体{}可以省略

  4. 函数默认的访问权限是public,此外也可以通过private,protected来修饰访问权限

  5. 函数前可以用override,final来修饰

  6. scala可以根据函数的返回值自动推断出函数的返回值类型

  7. 注意:如果函数和方法体之间没有=,则函数的返回值类型一律为Unit(空类型)

  8. scala函数支持默认参数机制,形式:
    def 函数名(形参名:参数类型=默认值)={}
    注意,默认值的类型要和形参类型一致

  9. 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
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值