object SparkTest002 {
def main(args: Array[String]): Unit = {
//date : 2015/12/29
//tuple test
val info = (5, "test", true)
print(s"first: ${info._1}, second: ${info._2}, third: ${info._3}\n")
val kv = "src" -> "dst"
print(s"first: ${kv._1}, second: ${kv._2}\n")
/*
* Chapter 3: Expressions and Conditionals
*/
val amount = {
val x = 5 * 20
x > 100
}
print(s"amount is : ${amount}\n")
val trippleNested = {
val a = 1;
{
val b = a + 2;
{
val c = b + 4
c
}
}
}
print(s"trippleNested : ${trippleNested}\n")
if (1 > 0) print("1 bigger than 0\n")
val x = 2;
val y = 3;
var res1 = if (x < y) x else y
val res2 = if (x > 100000) x // not safe, missed else branch
print(s"res: ${res2}\n")
val res3 = x > y match {
case true => {
x * 2
}
case false => {
y * 2
}
}
print(s"res: ${res3}\n")
val date = "monday"
val isValid = date match { // scala MatchError when missing the wildcard operator
case "mon" | "tue" => "yes"
case "thu" | "wen" => "no"
case _ => ""
}
print(s"isValid: ${isValid}\n")
for (i <- 1 to 3) print(s"count: ${i}\n")
print("\n")
for (i <- 1 until 3) print(s"count: ${i}\n")
print("\n")
val record = for (i <- 1 to 5) yield {i}
print(s"record size: ${record.size}\n")
for (i <- 1 to 5) print(s"${i}\n")
val odds = for (i <- 0 to 15 if i % 3 == 0) yield i
for (i <- odds) print(s"num: ${i}\n")
val line = "hello,world,,!"
for {
s <- line.split(",")
if s != null
if s.size != 0
} {
print(s"word: ${s}\n")
}
// nested iterators
for {
x <- 1 to 2
y <- 1 to 3
} {
print(s"nested value: ($x, $y)\n")
}
// value binding in for loop
val pows = for (i <- 0 to 8; pow = 1 << i) yield pow
for (i <- pows) print(s"$i\t")
val pows1 = for {
i <- 0 to 10
pow = 1 << i
} {
print(s"$pow\t")
}
}
}