【发布时间】:2011-10-06 21:05:53
【问题描述】:
假设我们有这样一个类:
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 成为第一条语句。
那么解决这个问题的方法是什么?
【问题讨论】:
标签: scala constructor overloading