patkua@work

Constructor work in Scala

In the java/ruby world, I am used to ensuring my objects are created in a valid state. This often means validating/converting constructor arguments into a format necessary for the rest of the class to do its work. In java, the code (non-compilable) might look like:

public class MyObject {
  ...

  public MyObject(Set<String> values) {
     this.internalRepresentation = convertToLowerCase(values)
  }

  ...
}

In scala, most examples out there seem to only chain constructors, and not necessarily do any work to that. I looked on stackoverflow and found this answer although it doesn’t feel particularly clean to me for some reason. My scala code now looks like this:

class MyObject(var values: Set[String]) {
  values = values.map(s => s.toLowerCase)
  ...
}

What I don’t like about this is that I had to elevate my field to being mutable, or had to have two immutable fields on the class (the temporary one for the constructor, and the one that I really want to use). The tests are passing, but I’m sure there is a better way.

Exit mobile version