Scala - Global variable get the value in a function

时间:2018-02-03 10:17:03

标签: scala variables global

I am a beginner of Scala.

I immediately get a problem.

Let's say:

I have a Vector variable and 2 functions. The first one function is calling 2nd function. And there is a variable in 2nd function is what I need to get and then append it to Vector. (Without returning the variable in 2nd function.)

The structure looks like this:

def main(args: Array[String]): Unit = {
    var vectorA = Vector().empty

}
def funcA(): sometype = {
    ...
    ...
    ...
    funcB()
}
def funcB(): sometype = {
    var error = 87

}

How can I add error variable in global Vector?

I tried to write vectorA :+ error but in vain.

1 个答案:

答案 0 :(得分:1)

You could do the following:

def main(args: Array[String]): Unit = {
    val vectorA = funcA(Vector.empty)

}

def funcA(vec: Vector): sometype = {
    ...
    ...
    ...
    funcB()
}
def funcB(vec: Vector): sometype = {
  // Here you could append, which returns a new copy of the Vector
  val error = 87
  vec :+ error

}

Keep in mind that, it is advisable to use immutable variables. Though not always this might be true, but for most of the applications that just involve doing some CRUD type logic, it is better to use immutable variables.