66.scala程式設計思想筆記——構造器和異常
歡迎轉載,轉載請标明出處:http://blog.csdn.net/notbaron/article/details/50458751
源碼下載下傳連接配接請見第一篇筆記。
構造器在建立對象。
New表達式除了傳回新建立的對象外,不能傳回其他任何資訊。
但傳回隻構造了部分的對象也是無用的,用戶端程式員會很輕易地認為這個對象是沒問題的。
解決這個問題有兩個基本方法:
a) 編寫一個簡單到不會失敗的構造器。
b) 在失敗時抛出異常。
伴随對象給了我們第三種選擇:因為apply通常被寫成一個用來生成新對象的工廠,并且他是方法而不是構造器,是以可以從aplly傳回錯誤資訊。如下:
package codelisting
import java.io.FileNotFoundException
class ExtensionException(name:String)
extendsException(
s"$name doesn't end with '.scala'")
class CodeListing(val fileName:String)
extends collection.IndexedSeq[String] {
if(!fileName.endsWith(".scala"))
throw newExtensionException(fileName)
val vec =io.Source.fromFile(fileName)
.getLines.toVector
defapply(idx:Int) = vec(idx)
def length =vec.length
}
object CodeListing {
defapply(name:String) =
try {
newCodeListing(name)
} catch {
case_:FileNotFoundException =>
Vector(s"File Not Found: $name")
case_:NullPointerException =>
Vector("Error: Null file name")
casee:ExtensionException =>
Vector(e.getMessage)
}
在建立一個測試代碼如下:
package codelistingtester
import com.atomicscala.AtomicTest._
class CodeListingTester(
makeList:String => IndexedSeq[String]) {
makeList("CodeListingTester.scala")(4) is
"classCodeListingTester("
makeList("NotAFile.scala")(0) is
"FileNot Found: NotAFile.scala"
makeList("NotAScalaFile.txt")(0) is
"NotAScalaFile.txt " +
"doesn'tend with '.scala'"
makeList(null)(0) is
"Error:Null file name"