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
}
//...
}
Constructors in Scala describe special methods used to initialize objects. When an object of that class needs to be created, it calls the constructor of the class. It can be used to set initial or default values for object attributes.
Abstract class cannot have a constructor.
Scala constructor is used for creating an instance of a class. There are two types of constructor in Scala – Primary and Auxiliary. Not a special method, a constructor is different in Scala than in Java constructors. The class' body is the primary constructor and the parameter list follows the class name.
The primary constructor of a Scala class is a combination of: The constructor parameters. Methods that are called in the body of the class. Statements and expressions that are executed in the body of the class.
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:
// Primary constructor takes a String
class Foo(s: String) {
// Auxiliary constructor also takes a String?? (compile error)
def this(a: String) {
this(a)
}
}
This isn't anything to do with the fact that the constructor is no-args; the following compiles for example:
class Foo(s: String) {
// alternative no-arg constructor (with different signature from primary)
def this() {
this("Default value from auxiliary constructor")
}
}
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.
For what it's worth you can introduce an extra scope to "mark" the init code.
class Foo {
{
// init code here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With