简体   繁体   中英

Define a function parameter as a “var” in 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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM