Reputation: 1583
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
}
//...
}
Upvotes: 15
Views: 22528
Reputation: 297295
The init code is the body of the method. But you can do this, if it bothers you all that much:
class Foo {
locally {
//some init code
}
}
Upvotes: 5
Reputation: 103847
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.
Upvotes: 20
Reputation: 16859
For what it's worth you can introduce an extra scope to "mark" the init code.
class Foo {
{
// init code here
}
}
Upvotes: 14
Reputation: 13137
Well putting the init code in the class body is the only way to have a constructor without parameters. I suppose if you want you could do something like :
class Foo {
private def init {
//init code here
}
init()
}
that's as close as you're gonna get.
Upvotes: 5