第三章 scala循环

1 三个基本的循环表达式

scala> 1 to 10

res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> 1.to(10)
res1: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> 1 until 10
res2: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)

2 for循环简单应用
scala> for(i<-1 to 10){
     | print(i+"\t")
     | }

1       2       3       4       5       6       7       8       9       10

定义数组,并输出

scala> val arr=Array("one",34.5,"three")
arr: Array[Any] = Array(one, 34.5, three)

scala> for(i<-arr){
     | print(i+" ")
     | }
one 34.5 three 

3 嵌套寻循环

if后的表达式为推导

scala> for(i<-1 to 3;j<-7 to 9 if(i!=j)) print("i="+i+",j="+j+"\t")

i=1,j=7 i=1,j=8 i=1,j=9 i=2,j=7 i=2,j=8 i=2,j=9 i=3,j=7 i=3,j=8 i=3,j=9

4 yield将值封装到集合中

scala> val res=for(i<-1 until 10) yield i
res: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> println(res)

Vector(1, 2, 3, 4, 5, 6, 7, 8, 9)

5 scala中定义方法

scala> def mod(x:Int,y:Int):Int=x+y
mod: (x: Int, y: Int)Int
调用方法
scala> val res=mod(8,99)
res: Int = 107

6 scala中定义函数
scala> val res=(x:Int,y:Int)=>x+y
res: (Int, Int) => Int = <function2>
调用函数

scala> val z=res(9,6)

z: Int = 15

7 将函数当作方法的参数进行传递

定义方法mod2,并传递一个函数f作为方法的参数

scala> def mod2(f:(Int,Int)=>Int)=f(3,4)
mod2: (f: (Int, Int) => Int)Int

定义一个有两个参数的函数
scala> val fun=(x:Int,y:Int)=>x*y
fun: (Int, Int) => Int = <function2>
调用方法mod2并把定义好的函数fun作为参数进行传递,返回结果
scala> val x=mod2(fun)

x: Int = 12

8 将方法转换成函数

定义方法

scala> def mod(x:Int,y:Int):Int=x-y

mod: (x: Int, y: Int)Int
注意:将方法mod转换成函数时,方法名后与_之间有一个空格
scala> val fun=mod _
fun: (Int, Int) => Int = <function2>
调用转换后的函数
scala> fun(9,86)
res1: Int = -77

猜你喜欢

转载自blog.csdn.net/wshsdm/article/details/80377633