tags:

views:

177

answers:

3

I have a class where I like to initialize my var by reading a configfile, which produces intermediate objects/vals, which I would like to group and hide in a method. Here is the bare minimum of the problem - I call the ctor with a param i, in reality a File to parse, and the init-method generates the String s, in reality more complicated than here, with a lot of intermediate objects being created:

class Foo (val i: Int) {

    var s : String;

    def init () {
        s = "" + i 
    }

    init ()
}

This will produce the error: class Foo needs to be abstract, since variable s is not defined. In this example it is easy to solve by setting the String to "": var s = "";, but in reality the object is more complex than String, without an apropriate Null-implementation.

I know, I can use an Option, which works for more complicated things than String too:

var s : Option [String] = None

def init () {
    s = Some ("" + i) 
}

or I can dispense with my methodcall. Using an Option will force me to write Some over and over again, without much benefit, since there is no need for a None else than to initialize it that way I thought I could.

Is there another way to achieve my goal?

+4  A: 

var s : Whatever = _ will initialize s to the default value for Whatever (null for reference types, 0 for numbers, false for bools etc.)

sepp2k
I will test this too. :)
user unknown
I tested it, and it works too. :)
user unknown
+10  A: 

Instead of creating separate methods for initialization, you should perform the initialization using the following way :

class Foo(val i: Int) {
  var s: String = {
    var s0 = " "
    s0 += i
    // do some more stuff with s0
    s0
  }

  var dashedDate = {
    val dashed = new SimpleDateFormat("yy-MM-dd")
    dashed.format(updated)
  }

  // Initializing more than one field:
  var (x, y, z) = {
    var x0, y0, z0 = 0
    // some calculations
    (x0, y0, z0)
  }
}
missingfaktor
Why the downvote?
missingfaktor
I didn't commit my comment, yesterday? Well, now that I see it, your answer with a tuple in a block looks so obvious. I like it.
user unknown
A: 

Honestly, why are you using var? Why not just do:

val rootObject = readFile(filename)

This would make the most sense to me.

egervari
a) because the real object isn't a String, but mutable object. and b) there are more objects initialised by reading the file, for example an array, for which the dimensions are specified in the file, as well as the content of the array.
user unknown
Why is it mutable? you're missing the point.Also, val arrayBuffer = new ArrayBuffer[MyType]()and then arrayBuffer.toArray
egervari
If it was an unmutable val, I would understand that I can't declare it in line x and initialice it in line x+n | n>0. Therefore I mentioned that it is a var, not a val.
user unknown