How would one translate the following Java code to Scala?
class ClassA {
private int field1;
private int field2;
public ClassA() {
field1 = 1;
field2 = 2;
}
}
I can see two options:
class ClassA(val field1: Int, val field2: Int) {
....
}
Or
class ClassA {
val field1: Int = 1
val field2: Int = 2
}
What is recommended, and why?
An instance variable is a variable which is declared in a class but outside of constructors, methods, or blocks. Instance variables are created when an object is instantiated, and are accessible to all the constructors, methods, or blocks in the class. Access modifiers can be given to the instance variable.
The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable. Because val fields can't vary, some people refer to them as values rather than variables.
An instance variable is a class property that can be different for each object. You create an instance variable by declaring it in the class definition, outside of any method. Instance variables are important because they allow each object to have its own copy of the data.
Instance variables can be declared at the class level before or after use. Access modifiers can be given for instance variables. The instance variables are visible for all methods, constructors, and block in the class. Normally, it is recommended to make these variables private (access level).
There is no simple translation from Java to Scala, it depends on the context:
You see, there are so many considerations. I'd suggest to learn about the possibilities of Scala, and to play around with different approaches, else you get stuck in the "Scala as better Java" trap longer than needed.
This is the most direct translation to Scala:
class ClassA{
private var field1 = 1
private var field2 = 2
}
Note the usage of var
instead of val
. val
is an immutable field, corresponding to public final
in Java. Thus it cannot be changed later and providing a way to initialize such a field to the correct value for a given instance is important.
In order to decide what you want to use you should ask yourself the questions that are listed in Landei's answer.
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