0

I have the following scala code. In this code, I am passing a (global) string name to a function and want to change the string depending on the first argument as shown below:

def retVal(x: (String,String), y: => String) = {if (x._1 != "") {y = x._1;x} else (y,x._2)}

But when I run this code, I get the following error:

y = x._1
  ^
reassignment to a val

How can I modify the code, so that I get the global string variable get updated when I call this function?

1
  • You are probably doing something wrong. Normally you shouldn't need functions like your retVal. Can you show us context in which you are calling retVal? Commented Oct 18, 2016 at 15:25

1 Answer 1

1

Function arguments are by default immutable in Scala. You cannot assign the a value to the function parameter.

In your case you are trying to assign to a call by name param which is not at all possible.

Also mutating is bad instead return the value and assign it to a new variable.

But still if you want to mutate do something like this

object MutationBox {
 var globalString = ""

 def retVal(x: (String,String)) = {
  if (x._1.nonEmpty) {
    globalString = x._1
    x
   } else (globalString, x._2)
 }

}

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.