過程
在Scala中,定義函數時,如果函數體直接包裹在了花括號裏面,而沒有使用=連接,則函數的返回值類型就是Unit。這樣的函數就被稱之爲過程。過程通常用於不需要返回值的函數。 過程還有一種寫法,就是將函數的返回值類型定義爲Unit。
def sayHello(name: String) = "Hello, " + name
def sayHello(name: String) { print("Hello, " + name); "Hello, " + name }
def sayHello(name: String): Unit = "Hello, " + name
Lazy值
在Scala中,提供了lazy值的特性,也就是說,如果將一個變量聲明爲lazy,則只有在第一次使用該變量時,變量對應的表達式纔會發生計算。這種特性對於特別耗時的計算操作特別有用,比如打開文件進行IO,進行網絡IO等。
import scala.io.Source._
lazy val lines = fromFile(“C://Users//Administrator//Desktop//test.txt”).mkString
異常
在Scala中,異常處理和捕獲機制與Java是非常相似的。
try {
throw new IllegalArgumentException(“x should not be negative”)
} catch {
case _: IllegalArgumentException => println(“Illegal Argument!”)
} finally {
print(“release resources!”)
}
try {
throw new IOException(“user defined exception”)
} catch {
case e1: IllegalArgumentException => println(“illegal argument”)
case e2: IOException => println(“io exception”)
}