I have been using Scala for about a month now, and what I like most about it is how it allows you to write very concise code - even more so since I almost exclusively used Java for the last couple of years. I'd like to discuss a pattern I found myself using frequently when working with immutable objects/case classes, and I wonder if this might be something general enough to be added to the language (as an additional synthetic, autogenerated method for case classes).
I often use case classes whose values are immutable collections, such as Maps. In many use cases, I need to "modify" (in an immutable fashion) exactly one of the instance fields, say a map. Of course I could write obj.copy(map = obj.map.updated(key, value)), which however is inconvenient if obj is not a val, but a more complex expression. My first solution was to introduce methods such as
def withUpdatedMap(key: K, value: V) = copy(map = map.updated(key, value))
but this gets tedious as the number of use cases grows: what about mapValues, remove (-) and so on?
I finally came up with this solution: https://gist.github.com/misberner/eec5e74f759353da3384 , which allows me to rewrite the above concisely by using the underscore symbol, as, e.g.,
obj.updated(map = _.updated(key, value)), or obj.updated(map = _.mapValues(-_))
It might be a little bit ugly to use the same parameter names for functions that are used for the fields, but I think this definitely contributes to the readability and descriptiveness of the updated() invocation.
I almost made a habit of adding this method to my case classes, and I actually use it more often than the copy method now. I think it'd be very useful if the compiler would autogenerate this method, as it does with copy (even though implementing it by hand is not that big of a deal, but neither would it be to implement copy).
Looking forward to hear your opinions.
You received this message because you are subscribed to the Google Groups "scala-debate" group.
To unsubscribe from this group and stop receiving emails from it, send an email to