问题
Coming from the Java world, I don't see how the restrictions on the auxiliary constructors in Scala are helpful ..
In Java, I know we can have multiple constructors as long as their signatures are different.
In Scala, the first call in an auxiliary constructor needs to be another auxiliary constructor or the class's primary constructor. Why? Doesn't this make Scala more restrictive?
回答1:
Scala essentially guarantees that the primary constructor will always be called, so it gives a single point of entry to the class; FOREVER. You ALWAYS know that the primary constructor will be called, no matter which auxiliary constructor you use to create the object.
Did you even experience having all your nice initialization in your (say) argument-less constructor in Java, and then you (in the future) or someone else coming along creating another constructor and then your objects are not correctly initialized and start miss-behaving? Probably not the best design in the world, but I faced this, and it wasn't fun.
Well, in Scala you never have to worry about this, if you have something in your primary constructor it will always be called or else the code will not compile. In my vocabulary it's not a restriction, it's called "Peace of Mind".
回答2:
Scala doesn't support multiple constructors like Java. While this may seem like an inconvenience, in return you get less boilerplate. And with factory methods in the companion object you end up getting a richer syntax for construction.
Scala needs to have a primary constructor because you can include declarations in it and eliminate the tedious boilerplate of initializing a field in the constructor.
class Rectangle(val width: Int, val height: Int) {
def this(size: Int) = this(size, size)
}
Note that the 'val' keywords in the default constructor declare two public fields. The idiomatic Java equivalent would have a lot more boilerplate (two getters, plus initialization in the constructor).
Actually in practice most developers prefer factory methods in the companion object (e.g. Rectangle(4)
instead of new Rectangle(4, 4)
), which is more flexible overall.
来源:https://stackoverflow.com/questions/41727056/scala-what-is-the-benefit-of-auxiliary-constructors-always-having-to-call-anot