Logic in an overloaded constructor in scala
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
}
}
No comments:
Post a Comment