執行在重載的構造函數代碼假設我們有一類這樣的:之前調用這個()
import java.net.URL
import xml._
class SearchData(xml: Node) {
def this(url: URL) = this (XML.load(url))
}
,我們要執行之前調用this (XML.load(url))
一些代碼 - 比如測試與try
。人們預計,寫像這樣的工作:
class SearchData(xml: Node) {
def this(url: URL) {
try {
this (XML.load(url))
} catch {
case _ => this(<results/>)
}
}
}
,但它不會,因爲Scala的要求,您對this()
呼叫在重載的構造,在這種情況下try
第一條語句成爲第一個語句。
那麼這個問題的解決方案是什麼?
所申報的問題的一個很好的解決方案,但它不是一般的。可能這是我的錯,我宣佈了一個誤導性的小問題。無論如何檢查出http://stackoverflow.com/questions/7680442/executing-code-in-overloaded-constructor-prior-to-calling-this/7687567#7687567這有點演變您的解決方案 –