scala筆記-過程、lazy值和異常(6)
阿新 • • 發佈:2018-11-08
過程
在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
即使檔案不存在,也不會報錯,只有第一個使用變數時會報錯,證明了表示式計算的lazy特性。
val lines = fromFile("C://Users//Administrator//Desktop//test.txt").mkString lazy val lines = fromFile("C://Users//Administrator//Desktop//test.txt").mkString def 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") }