Say we have a class like this:
import java.net.URL
import xml._
class SearchData(xml: Node) {
def this(url: URL) = this (XML.load(url))
}
and we want to execute some code prior to calling this (XML.load(url))
- say test it with try
. One would expect that writing something like this would work:
class SearchData(xml: Node) {
def this(url: URL) {
try {
this (XML.load(url))
} catch {
case _ => this(<results/>)
}
}
}
but it won't, because Scala requires that you make the call to this()
the first statement in the overloaded constructor and in this case try
becomes the first statement.
So what would be the solution to this problem?
Constructors can be overloaded in a similar way as function overloading. Overloaded constructors have the same name (name of the class) but the different number of arguments. Depending upon the number and type of arguments passed, the corresponding constructor is called.
Constructors overloading vs Method overloading If we want to have different ways of initializing an object using different number of parameters, then we must do constructor overloading as we do method overloading when we want different definitions of a method based on different parameters.
Only the first statement should call another constructor. 16) What is the output of the below Java program with many constructors? Explanation: Constructor overloading allows constructors with different arguments at the same time.
Constructor functions are not inherited and their addresses cannot be referenced. When memory allocation is required, the new and delete operators are called implicitly.
def this(url: Url) = this(try {XML.load(url)} catch {case _ => <results/>})
More generally, the evaluation of the arguments has to happen before the constructor call, so you do that there (a block in scala is an expression, but write a routine, typically written in the companion object, if it is going to be too long). What you cannot do is have this code choose which other constructor you call. But as all of them must route to the primary one, you do not lose much. Also, you need the other constructor you call to have at least one argument. If there are several constructors, the primary one should normally not be the one without an argument (see Scala problem optional constructor)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With