sarthak sarthak - 4 days ago 5x
Scala Question

Passing function arguments by Name Scala

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?


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
   } else (globalString, x._2)