I’m still trying to wrap my head around Scala constructors
public class MyClass {
private String myString = null;
public MyClass() {
myString = "hello";
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Scala you would just do
This doesn’t look like the same thing, does it? But let’s look at the bytecode for what the Java code actually produces (let’s call that class
JavaConstructor):Java has effectively copied the
private String myString = null;into the constructor (note lines 5 and 6 wherenullis created and stored). So that whole thing about settingmyStringtonullwas a complete waste of effort; you load it and then immediately overwrite it.Now if we look at the corresponding Scala:
we see it’s as efficient as one would hope (and reflects the code).
Then the question is: why might you want to do it the way you did in Java? Well, maybe you have multiple constructors and some of them will set
myStringand some won’t! Setting it tonullis a way to remind yourself that you had better initialize it before you use it.But Scala won’t let you do that. Scala really only allows one constructor; the others are just aliases that call that one constructor. You can make it private and load it up with lots of parameters if you need to, but the point is that having multiple constructors some of which set critical data and some of which do not is actually a rather failure-prone process. Better to do it just once, and write something like
if you really need to do that. Then again, maybe you only made it a
varbecause you were trying to set it differently in different constructors. With only one constructor, maybe there’s no need for that:But maybe now that it’s set correctly, we don’t really need it to be private.
and maybe if it often isn’t set, we should use an option instead:
and then you’d have something that looks more like idiomatic Scala.