简体   繁体   English

在Scala中将函数参数定义为“var”?

[英]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? 编译器抱怨说有一个val的重新分配,所以没有把它改成一个可变的地图,有没有办法像案例类那样说“var k:Map ...”?

Thanks! 谢谢!

What you're asking for is a pass by reference argument. 你要求的是一个参考传递参数。 The JVM doesn't have those and neither does Scala.* JVM没有那些,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: 或者返回两者,或者如果你必须返回T ,写一个包装类:

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. 当然,必须以某种方式使用闭包来改变外部上下文中的变量,事实上Scala所做的就是使用与上面显示的类似的包装类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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