I am trying to add some processing logic in an overloaded constructor, but cannot seem to get it working.
Here is a simplified example of what I want to do:
class FooBar(val x: String, val y: String) {
this(z: String) = {
// DO SOME ARBITRARY CODE
val x = // SOME ARBITRARY PROCESSING USING z
val y = // SOME ARBITRARY PROCESSING USING z
this(x, y)
}
}
However, I am getting a compilation error:
: 'this' expected but 'val' found
This is a very simple task in Java, I would simply set the x, y
instance variables from 2 separate constructors.
Here is my Java equivalent of what I would like to accomplish:
class FooBar {
public String x;
public String y;
public FooBar(String x, String y) {
this.x = x;
this.y = y;
}
public FooBar(String z) {
// DO SOME ARBITRARY CODE
this.x = // SOME ARBITRARY PROCESSING USING z
this.y = // SOME ARBITRARY PROCESSING USING z
}
}
=================== EDIT ==================
I decided to go with @om-nom-nom's approach using a companion object. However as @om-nom-nom pointed out there is no way to get around the missing new
invocation. Therefore in order to make my constructors consistent, I overloaded the apply
method in the companion object:
class FooBar(val x: String, val y: String)
object FooBar {
def apply(x: String, y: String) = new FooBar(x, y)
def apply(z: String) = {
// DO SOME ARBITRARY CODE
val x = // SOME ARBITRARY PROCESSING USING z
val y = // SOME ARBITRARY PROCESSING USING z
new FooBar(x, y)
}
}
FooBar(someX, someY)
FooBar(someZ)