Partial Function
package com.sparktest /** * */ object PartialFunctionTest { def main(args: Array[String]): Unit = { val sample = 1 to 10 val isEven:PartialFunction[Int,Unit] = { case x if x % 2 == 0 => println(x + " is even!") } val isOdd:PartialFunction[Int,Unit] = { case x if x % 2 == 1 => println(x + " is odd!") } // val evenNumbers = sample collect isEven // 等价于 val evenNumbers = sample.collect(isEven) // evenNumbers.foreach(println) val numbers = sample.map(isEven orElse isOdd) // numbers.foreach(println) } }
Exception
package com.sparktest import java.io.IOException /** * */ object ExceptionAndLazyTest { def main(args: Array[String]): Unit = { try { 1 / 0 } catch { case ioException: IOException => println("IOException: " + ioException.toString()) case illegalArgs: IllegalArgumentException => println("IllegalArgumentException: " + illegalArgs.toString()) case arithmeticException:ArithmeticException => println("ArithmeticException" + arithmeticException.toString()) } } }
Lazy
package com.sparktest import java.io.IOException /** * */ object ExceptionAndLazyTest { def main(args: Array[String]): Unit = { lazy val score = 100 println("......" + score) println("......") } }