Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a function parameter as a "var" in Scala?

Tags:

syntax

scala

I have a function like this:

private def add[T](n: String, t: T, k: Map[String,T]): T = { k += (n -> t); t }

the compiler complains that there is a reassignment to val, so short of changing this to a mutable map, is there a way to say something like "var k: Map..." as in a case class?

Thanks!

like image 301
Alex Avatar asked Jun 30 '12 19:06

Alex


1 Answers

What you're asking for is a pass by reference argument. The JVM doesn't have those and neither does Scala.*

You will either have to return the updated map:

private def add[T](n: String, t: T, k: Map[String,T]): Map[String,T] = k + (n -> t)

or return both, or if you must return T, write a wrapper class:

case class Vary[A](var value: A) { def apply() = value }
private def add[T](n: String, t: T, k: Vary[Map[String,T]]) = { k.value += (n -> t); t }

val map = Vary( Map.empty[String,Int] )
add("fish", 5, map)
map()  //Map[String,Int] = Map(fish -> 5)

*Well, not directly. Of course, one must change vars in an outer context somehow with closures, and in fact what Scala does is use a wrapper class much like the one I show above.

like image 175
Rex Kerr Avatar answered Sep 20 '22 14:09

Rex Kerr