Search code examples
scalavariablesscala-breeze

Forward reference error in a for loop Scala


This is a code that is written in Scala :

for (i <- 0 until 10) {
  if (i > 0) {
    val new = theta(i * 5)
  }
  // using variable new

  val theta = DenseVector.zeros[Int]((i + 1) * 10)
  // doing operations on theta
}

every iteration has own variables and order of variables can't change because between them doing some operations.

when i running this code it shows this error:

Wrong forward reference

how can i resolve this problem?


Solution

  • Replace theta before if expression by making theta method.

    def theta(i: Int) = DenseVector.zeros[Int]((i + 1) * 10)
    for (i <- 0 until 10) {
      if (i > 0) {
        val new = theta(i * 5)
      }
      // doing operations on theta
    }