声明变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| object Hello { def main(args: Array[String]): Unit = { println("Hello Scala")
val i = 1
var s = "Hello Scala"
val str: String = "Hello Spark" } }
|
常用类型
Scala和Java一样,有7种数值类型Byte、Char、Short、Int、Long、Float、Double类型和1个Boolean类型。
条件表达式
Scala的条件表达式比较简洁,定义变量时加上if else判断条件。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
def conditionalExpression(num1: Int, num2: Int): Unit = { if (num1 > num2) { println(num1 + " > " + num2) } else if (num1 == num2) { println(num1 + " = " + num2) } else { println(num1 + " < " + num2) } }
|
块表达式
定义变量时用 {} 包含一系列表达式,其中块的最后一个表达式的值就是块的值。
1 2 3 4 5 6 7 8 9 10 11 12
| def lump (): Unit ={ val a = 10 val b = 20 val result = { a + b } println(result) }
|
循环
在scala中有好几种循环,其中for循环和while循环用的比较多
for循环:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
def foreachExpression(num1: Int, num2: Int): Unit = { val arr: Range = num1.until(num2) arr.foreach(e => { print(e + " ") }) println() }
def forExpression(num1: Int, num2: Int): Unit = { val arr: Range = num1.until(num2)
for (a <- arr if a % 2 == 0) { println("质数: " + a) } }
|
while循环:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
def whileExpression(): Unit = { var count = 10
while (count > 0) { print(count + " ") count -= 1 } println() }
def dowhileExpression(): Unit = { var count = 10
do { print(count + " ") count -= 1 } while (count > 0)
println() }
|
其他循环:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
def toExpression(num1: Int, num2: Int): Unit = { val arr: Inclusive = num1.to(num2) println(arr.toList) }
def rangeExpression(num1: Int, num2: Int): Unit = { val arr: Range = Range(num1, num2) println(arr.toList) }
def untilExpression(num1: Int, num2: Int): Unit = { val arr: Range = num1.until(num2) println(arr.toList) }
|
break 终止循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
def breakExpression(num1: Int, num2: Int): Unit = { val arr: Inclusive = num1.to(num2) val loop = new Breaks;
loop.breakable { for (a <- arr) { print(a + " ") if (a == 5) { loop.break() } } }
println() }
|