Scala学习——函数

时间:2023-03-10 03:24:09
Scala学习——函数

一、函数的定义(def)

Scala学习——函数

object FunctionApp {

//定义函数:方法体内最后一行为返回值,不需要使用return
def add(a:Int,b:Int):Int={
a + b
} //定义函数:函数体就一行,花括号可以省略
def add1(a:Int,b:Int)=a+b //定义函数:无参函数在调用时括号可以省略
def add2()=9+9 //定义函数:无返回值的函数
def say(): Unit ={
println("hello")
} //定义函数:带参数无返回值的函数
def say(name:String): Unit ={
println("hello"+name)
} //默认参数:在函数定义时允许指定参数的默认值,传入值时会覆盖默认值
def sayName(name:String = "Rdb"):String={
name
} //命名参数:在调用参数时,可以不按参数的顺序传入,可以根据参数的名称传递
def add3(a:Int,b:Int):Int={
a + b
} //可变参数:传入的参数个数不确定
def sum(number:Int*)={
var result = 0
for(num <- number){
result += num
}
result
}
}

二、scala中的循环表达式

1)to

1 to 10 :表示1到10,包括1和10,也可以写作:1.to(10)。

默认步长为1,可以手动指定步长

scala> (1 to 10).toList
res4: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> (1.to(10)).toList
res5: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> (1 to 10 by 2).toList
res6: List[Int] = List(1, 3, 5, 7, 9)

2)Range

Range也表示一段范围,但是与to的区别是:to是左闭右闭,而Range是左闭右开,也可以手动指定步长

scala> Range(1,10).toList
res8: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9) scala> Range(1,10,2).toList
res9: List[Int] = List(1, 3, 5, 7, 9)

3)until

until也是是左闭右开区间

scala> (1 until 10).toList
res10: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9) scala> (1.until(10)).toList
res11: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9) scala> (1 until 10 by 2).toList
res12: List[Int] = List(1, 3, 5, 7, 9)

3)for循环

object FunctionApp {

  def main(args: Array[String]): Unit = {

    //用to,until,Range 做for循环
for(i <- 1.to(10)){
println(i)
} //定义数组
val students = Array("lucy","jack","mark","lili");
//常规遍历数组
for(student <- students){
println(student)
}
//foreach遍历数组,类似java里的lambda表达式
students.foreach(s => println(s)) }
}

4)while

object FunctionApp {

  def main(args: Array[String]): Unit = {
var i = 0;
while(i < 100){
print(i + " ")
i += 1
}
}
}

5)do...while

object FunctionApp {

  def main(args: Array[String]): Unit = {
var i = 0;
do{
print(i + " ")
i +=1
}while(i < 100)
}
}