class Foo() {
val array // how do I leave initialization till later?
def initializeArray(size : Int) = array = Array.ofDim[Int](size)
}
The above code won’t compile, so how do I initialize my array at a later time?
Edit
Suppose I need to read a file that has a matrix of integer, and I want to represent the matrix as a two dimensional array. Of course, I am parsing the file inside the Foo class and the dimension of the matrix won’t be known until the parsing is done.
One simple way would be to just initialize it to
null. To do this you would need to specify a type,Array[Int]and to make it avar(instead ofval) so that you could change it later:However, this is not very good practice in Scala. It might be better to use an
Option:This tells a user, explicitly, that it is possible that
arraymay not be set to anything, and avoidsNullPointerExceptions. You can read more aboutOptionon StackOverflow or elsewhere.Finally, the best designs in Scala rely on immutable classes. In such a case, you would defer creation of the
Foountil you actually know what you want to put in it. However, without knowing anything else about your design, it’s hard to say how best to set this up.EDIT: Based on your description, I would separate your design into two parts: a method for parsing the file, and an immutable
Foofor storing the final result.Then you could just say:
and the
foowould be an complete, immutableFoo.