0

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.

2
  • You should first read about thé design of thé Scala collections and immutability (using var and mutation of variable should only be thé last option, un some particularité cases) Commented Feb 3, 2018 at 11:06
  • Scala is not wierd, rather the user! You need to understand the principles behind Scala and then you should approach your problem! Commented Feb 3, 2018 at 11:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.