enlait enlait - 5 months ago 34
Scala Question

scala constructor-local variables again

I am porting my java code to scala, and have a constructor that does quite some stuff:

  1. open hibernate session to load data

  2. do loading (now the session is kept open! I need lazy loading further on)

  3. perform some operations on loaded data and put in containers

  4. tie containers with their consumers

  5. ..blah blah

  6. close session

The constructor produces quite a number (~20) of object members, that are final (val in scala). Their creation is not independent, also note that session. Obviously I don't want the session and other temporary stuff to become constructed instance members. How do I do that in scala?

Similar questions have been already asked before:

Answers given in previous topics suggest either returning a tuple of ~20 fields from initialization method, or creating a private constructor that takes those ~20 values as parameters from companion object apply method. Either seems pig ugly to me.

So far the most sensible approach seems to declare those fields as vars, not vals, and reassign them in some initialization method, which also kinda smells.


I have a technically correct solution, but it might not be what you wanted, because it introduces a lot of verbocity

trait Example {
  val a1 : Int
  val a2 : Int
  val a3 : Int
  val a4 : Int
  val a5 : Int
  val a6 : Int
object Example {
  def apply(seed : Int) : Example = {
    val x1 = seed + 1
    val x2 = x1 * 2
    val x3 = x2 / 3
    val x4 = x3 + x1
    val x5 = x4 * x2
    val x6 = x5 - x4
    new Example {
      override val a1 = x1
      override val a2 = x2
      override val a3 = x3
      override val a4 = x4
      override val a5 = x5
      override val a6 = x6

So there is no constructor neither initializing method that takes many of variables, but they are passed via trait extending