scala控制结构

#判断

scala> def min(x:Int,y:Int):Int={
 var a=x
 if(x>y) a=y
 return a
 }

scala> min(1,2)
res1: Int = 1

#循环    ##引申:函数式编程里面尽量使用常量,所以尽量避免 while do? 变量?

while (A) B

do B while A

scala> var m=3
scala> while (m!=0){

println(m)
 m-=1
 }

3
2
1

#枚举

for (i<-e) E(i)

scala> for ( i <- 1 to 4)
               println("No."+i)
No.1
No.2
No.3
No.4

scala> for(i <- 1 to 4; j <- 1 to 2) println(i+j)
2
3
3
4
4
5
5
6

#

scala> var No = for ( i <- 1 to 4) yield i

No: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4)

#Practise

for (i <- "HELLO") yield i

for(i<-1 to 2) yield i.toChar

for(i <- "HELLO";j<- 1 to 2) yield(i+j).toChar

for(i<- 1 to 2;j<- "HELLO") yield(i+j).toChar

#匹配(match)

a match{

case e1 => E1

case _ => ...

}

#异常处理(throw/try)

try {...} catch{case ...;case ...} finally(A.close()}

#输入输出

上一篇:事件冒泡与事件委托 -Tom


下一篇:WEB用户访问控制方法