[ACCEPTED]-Scala instance variables best practice-scala

Accepted answer
Score: 20

There is no simple translation from Java 6 to Scala, it depends on the context:

  • Are the variables mutable in Java? If yes (else they should be final in Java): Would it make sense to make them immutable in Scala?
  • Should the constructor stay public in Scala? Would be a factory (e.g. an apply method in the companion object) more apropriate?
  • Why are are the variables private? Do they have getters and/or setters?
  • When are the variables needed, would it make sense to make them lazy?
  • If the values are immutable and exposed, would they be useful in pattern matching? Would a case class be the right choice?
  • Could the variables be grouped (e.g. in a tuple) in order to simplify API and access?

You 5 see, there are so many considerations. I'd 4 suggest to learn about the possibilities 3 of Scala, and to play around with different 2 approaches, else you get stuck in the "Scala 1 as better Java" trap longer than needed.

Score: 10

This is the most direct translation to Scala:

class ClassA{
  private var field1 = 1
  private var field2 = 2

Note 8 the usage of var instead of val. val is an immutable 7 field, corresponding to public final in Java. Thus it 6 cannot be changed later and providing a 5 way to initialize such a field to the correct 4 value for a given instance is important.

In 3 order to decide what you want to use you 2 should ask yourself the questions that are 1 listed in Landei's answer.

Score: 7

The biggest difference between the two is 8 that the class parameter one can be used 7 as constructor. If you want the constructor 6 to have no parameters, as your Java example, then 5 you need to use the second one, plus adding 4 the private modifier as suggested by @Debilski.

Another 3 option would be to use default parameters 2 in the constructor. That way the fields 1 could be changed if needed:

class ClassA (private val field1: Int = 1, private val field2: Int = 2)

// Using defaults
val a = new ClassA

// Setting new values
val b = new ClassA(3, 4)
Score: 4

If you want to have private fields, why 1 not declare them private?

class ClassA {
  private val field1: Int = 1
  private val field2: Int = 2
Score: 1

If you always want that field1 and field2 have 4 the same value for each instance of the 3 class A, I would suggest to put them in 2 a companion module:

object A {
  private val field1 = 1
  private val field2 = 2

And then use them in 1 class A:

class A {
  def complexInternalComputation = 2*A.a

or this way:

class A {
  import A._
  def complexInternalComputation = 2*a

More Related questions