How do you provide overloaded constructors in Scala?
+6
A:
class Foo(x: Int, y: Int) {
def this(x: Int) = this(x, 0) // default y parameter to 0
}
landon9720
2009-07-07 23:16:54
Wait... Why did you post the question if you already know the answer?
musicfreak
2009-07-07 23:18:52
1. I wanted to see if SO could answer the question faster than I could look it up (no, it can't).2. I wanted to contribute a little somethin' somethin'
landon9720
2009-07-07 23:21:43
Fair enough. :)
musicfreak
2009-07-07 23:52:43
Also the site FAQ does say it's accepted practice to answer your own question - it's always nice to have an answer to a common question, even if it was asked by someone who already knows :)
Calum
2009-07-08 15:25:15
+14
A:
It's worth explicitly mentioning that Auxiliary Constructors in Scala must either call the primary constructor (as in landon9720's) answer, or another auxiliary constructor from the same class, as their first action. They cannot simply call the superclass's constructor explicitly or implicitly as they can in Java. This ensures that the primary constructor is the sole point of entry to the class.
class Foo(x: Int, y: Int, z: String) {
// default y parameter to 0
def this(x: Int, z: String) = this(x, 0, z)
// default x & y parameters to 0
// calls previous auxiliary constructor which calls the primary constructor
def this(z: String) = this(0, z);
}
Jon McAuliffe
2009-07-08 07:10:03