tags:

views:

1843

answers:

2

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
Wait... Why did you post the question if you already know the answer?
musicfreak
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
Fair enough. :)
musicfreak
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
+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
which is A Good Thing(tm)
skaffman
Add the code sample to your answer, and I'll mark it correct.
landon9720