I may be having a silly problem here… I can’t seem to figure out how to make a constructor without parameters in Scala. I know I can just write the whole thing in the class body (especially because it’s the only constructor I need), but it doesn’t quite feel right.
What I have:
class Foo {
//some init code
//...
}
What I’d like (but doesn’t work as it wants me to call another constructor first):
class Foo {
// The only constructor
def this() = {
//some init code
}
//...
}
All classes in Scala have a primary constructor and optionally some auxiliary constructors (which must defer to the primary constructor or another auxiliary constructor).
The issue in your case is that in both cases you’ve defined the primary constructor as taking no arguments – and then in the second case you try to define an auxiliary constructor with the same signature. This doesn’t work, for the same reason that the following wouldn’t compile:
This isn’t anything to do with the fact that the constructor is no-args; the following compiles for example:
In particular, in your second example, your comment “the only constructor” is wrong. Auxiliary constructors are always secondary to the primary constructor, and cannot ever be the only constructor.
FWIW, the first example is the only option open to you, but it looks fine to me. If you’ve just started using Scala I’m sure it will start to feel right soon enough – and it’s important to eschew Java-esque ways of doing things when there are more idiomatic alternatives.