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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With