for循环Scala中的前向引用错误

Forward reference error in a for loop Scala

这是用 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
}

每次迭代都有自己的变量,变量的顺序不能改变,因为它们之间有一些操作。

当我 运行 此代码时,它显示此错误:

Wrong forward reference

我该如何解决这个问题?

通过theta方法替换if表达式之前的theta

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
}