一、条件表达式

scala> val x = 1
x: Int = 1

scala> if(x > 0) true else false
res4: Boolean = true

// if语句可以直接赋值给一个变量
scala> val a = if(x > 0) true else false
a: Boolean = true

// 通过变量执行if语句
scala> a
res5: Boolean = true

二、循环表达式

to
until
Range

tountil 都是通过 Range 实现的

scala> 1 to 10  // 包含左右区间
res6: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> Range(1, 10) // 包含左区间,不包含右区间
res7: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> Range(1, 10, 2) // step 为2,step 不能为0
res8: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)


scala> Range(10, 1, -1) // step 为负数时
res10: scala.collection.immutable.Range = Range(10, 9, 8, 7, 6, 5, 4, 3, 2)

to和until的两种写法,作用一模一样

1 to 10
1.to(10)

1 until 10
1.until(10)

实现 for

  for (i <- 1 to 10){
    println(i)
  }

输出:1 2 3 4 5 6 7 8 9 10

  for (i <- 1 to 10 if i % 2 == 0){
    println(i)
  }

输出:2 4 6 8 10

for 遍历数组

  val courses = Array("Hadoop", "Spark SQL", "Spark Streaming", "Storm", "Scala")
  for (course <- courses){
    println(course)
  }

foreah 循环遍历

courses.foreach(course => println(course))

while 循环求和

var (num, sum) = (100, 0)
  while(num > 0){ // 出口
    sum = sum + num
    num = num -1 // 步长
  }
  println(sum)