In Mercury I can use:
A = B^some_field := SomeValue
to bind A to a copy of B, except that some_field is SomeValue instead of whatever it was in B. I believe the Haskell equivalent is something like:
a = b { some_field = some_value }
Does Scala have something like this for “modifying” immutable values. The alternative seems to be to have a constructor that directly sets every field in the instance, which isn’t always ideal (if there are invarients the constructor should be maintaining). Plus it would be really clunky and much more fragile if I had to explicitly pass every other value in the instance I want to have a modified copy of.
I couldn’t find anything about this by googling, or in a brief survey of the language reference manual or “Scala By Example” (which I have read start-to-finish, but haven’t absorbed all of yet, so it may well be in there).
I can see that this feature could have some weird interactions with Java-style access protection and subclasses though…
You can use case classes for this, but you don’t have to. Case classes are nothing magical – the modifier
casejust saves you a lot of typing.The copy method is realized by the use of named and default parameters. The names are the same as the fields and the defaults are the current values of the fields. Here’s an example:
You can use this just like the copy method on case classes. Named and default parameters are a very useful feature, and not only for copy methods.