简体   繁体   中英

Scala adding the result of a function call to the value in a map

I came across a weird functionality of Scala where the following two are not equivalent:

var map = Map[A,B]() 
map += ( key -> (valueGen(key)))

does not give the same result as

var map = Map[A,B]() 
val result = valueGen(key)
map += ( key -> result)

The second snippet does what you expect it to while the first one does not add correctly to the map, it instead overwrites the previous value so that the map only contains the most recently written value to it instead of all the values added into it.

I've seen this before, and it only causes problems when the valueGen function and this code is recursive together. I believe this is because expressions in parentheses are not guaranteed to be executed first. Parentheses only bind operators. Scala must be interpreting the += on the map like this:

map = map + (expression)

When it executes map + (expression) , it reads the map operand to the plus operator first and holds it. Then it attempts to evaluate (expression) . In the case (expression) contains the call to the valueGen function, it makes the call and then adds it to the cached map from this particular call. If the call to valueGen ends up recursing around and calling this function (and modifying the map first), this will overwrite those changes with the cached version from this call + the result. That is why you want to call the valueGen function separately from the += operator if your function is recursive.

When I run

object test {
    def main(args: Array[String]) {
        var map = Map[String,Int]()
        map += ("hello" -> (valueGen("hello")))
        map += ("bye" -> (valueGen("bye")))
        println(map)
    }

    def valueGen(x: String) = x.length
}

I get

Map(hello -> 5, bye -> 3)

Could you provide a runnable example of what you are seeing?

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