In Scala, all classes have a primary constructor, specified directly after the class name:
class Test (x: Int, y: Int) { ... }
Code to further initialize the object goes right into the body of the class:
class Test (x: Int, y: Int) { if (x == 42 && y == 23) error("no jokes, please") }
Variables and values specified in the class body will be visible as fields of class instances. If you need to write complex initialization code that requires local variables, but do not want to add those variables to the class itself, you have multiple options:
Using tuples and a local scope:
class Test(in: String) { val (x, y) = { // complex calculation val res1 = ... val res2 = ... (res1, res2) } }
Lazy values, i.e. fields that are initialized when required:
class Test(in: String) { lazy val (x, y) = parse(in) def parse(in: String) = { ..., (res1, res2) } }
Another way is using a factory:
abstract class Test { val x: Int val y: Int } object Test { def apply(in: String) = { // calculation ... new Test { val x = res1 val y = res2 } } }