sarthak
sarthak

Reputation: 794

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?

Upvotes: 0

Views: 115

Answers (1)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

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)
 }

}

Upvotes: 1

Related Questions