Accessing Constants which rely on a list buffer to be populated Scala

69 views Asked by At

Encountering a problem whereby I am specifying Private Constants at the start of a scala step definiton file which relies on a List Buffer element to be populated, however when compiling I get a 'IndexOutOfBoundsException' because the list is empty initially and only gets populated later in a for loop. For Example I have the following 2 constants:

private val ConstantVal1= globalExampleList(2)
private val ConstantVal2= globalExampleList(3)

globalExampleList is populated further down in the file using a for loop:

 for (i <- 1 to numberOfW) {
    globalExampleList += x.xy }

This List Buffer adds as many values as required to a global mutable ListBuffer.

Is there a better way to declare these constants? I've tried to declare them after the for loop but then other methods are not able to access these. I have around 4 different methods within the same file which use these values and instead of accessing it via index each time i thought it would be better to declare them as a constant to keep it neat and efficient for whenever they require changing.

Thanks

2

There are 2 answers

1
Dmytro Mitin On BEST ANSWER

You can create list buffer of necessary size with default value and populate it later:

val globalExampleList: ListBuffer[Int] = ListBuffer.fill(numberOfW)(0)

for (i <- 0 until numberOfW) {
  globalExampleList(i) = x.xy 
}

But ConstantVal1, ConstantVal2 will still have original default value. So you can make them vars and re-assign them after you populate the buffer.

Your code seems to have a lot of mutations and side effects.

0
蘇哲聖 On

You have 2 ways to go. First you can use lazy modifier

private lazy val ConstantVal1= globalExampleList(2)
private lazy val ConstantVal2= globalExampleList(3)

Or you can write the two lines after the for loop.

val globalExampleList = XXXX
for (i <- 1 to numberOfW) { globalExampleList += x.xy }
private val ConstantVal1= globalExampleList(2)
private val ConstantVal2= globalExampleList(3)