initialise a var in scala
Posted
by user unknown
on Stack Overflow
See other posts from Stack Overflow
or by user unknown
Published on 2010-05-02T17:34:32Z
Indexed on
2010/05/02
17:38 UTC
Read the original article
Hit count: 207
scala
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?
© Stack Overflow or respective owner