Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialise a var in scala

Tags:

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?

like image 213
user unknown Avatar asked May 02 '10 17:05

user unknown


People also ask

How do you create a String variable in Scala?

In scala we can create string in two ways using string literal and b defining string. In this example we are creating a string object by assigning a String keyword before the literal. In this syntax we are using string literal to create a string object. Both the ways are same as java with some little modification.

How do you initialize a variable in Scala?

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


1 Answers

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

like image 153
sepp2k Avatar answered Oct 06 '22 01:10

sepp2k